Skip to content
generated from LgoLgo/.github

Lightweight reentrant lock implemented in Go.

License

Notifications You must be signed in to change notification settings

LgoLgo/geentrant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

geentrant

English | 中文

Lightweight reentrant lock implemented in Go.

Installation

To install this package, you need to install Go and set your Go workspace first.

  1. You first need Go installed, then you can use the below Go command to install geentrant.
go get -u github.com/LgoLgo/geentrant
  1. Import it in your code:
import "github.com/LgoLgo/geentrant"

Quick start

# assume the following codes in example folder
$ cat example/main.go
package main

import (
	"fmt"
	"sync"

	"github.com/LgoLgo/geentrant"
)

func main() {
	var wg sync.WaitGroup
	rm := &greetrant.RecursiveMutex{}

	// This first goroutine locks and unlocks the recursive mutex recursively 5 times.
	wg.Add(1)
	go func() {
		for i := 0; i < 5; i++ {
			rm.Lock()
			fmt.Println("goroutine 1 locked")
		}
		for i := 0; i < 5; i++ {
			rm.Unlock()
			fmt.Println("goroutine 1 unlocked")
		}
		wg.Done()
	}()

	// This second goroutine tries to unlock the mutex without locking it, which should fail with a panic.
	wg.Add(1)
	go func() {
		defer func() {
			if r := recover(); r == nil {
				fmt.Println("Unexpected result: should have panicked")
			}
			wg.Done()
		}()
		rm.Unlock()
	}()
	wg.Wait()
}

License

This project is under the Apache License 2.0. See the LICENSE file for the full license text.