greetrant

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2023 License: Apache-2.0 Imports: 6 Imported by: 0

README

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.

Documentation

Index

Constants

View Source
const (
	Name    = "geentrant"
	Version = "v0.1.0"
)

Name and Version info of this framework, used for statistics and debug

Variables

This section is empty.

Functions

func GoID

func GoID() int64

Types

type RecursiveMutex

type RecursiveMutex struct {
	sync.Mutex
	// contains filtered or unexported fields
}

RecursiveMutex wraps a Mutex for reentrancy.

func (*RecursiveMutex) Lock

func (m *RecursiveMutex) Lock()

func (*RecursiveMutex) Unlock

func (m *RecursiveMutex) Unlock()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL