lock

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2024 License: BSD-3-Clause Imports: 1 Imported by: 10

README

Example

import "import.name/lock"
import "import.name/lock/unlock"

func ExampleLock() {
	var (
		mu    sync.Mutex
		count int
	)

	lock.Guard(&mu, func() {
		count++
	})

	n := lock.Guarded(&mu, func() int {
		return count
	})
	fmt.Println(n)
}

func ExampleUnlock() {
	var mu sync.Mutex

	mu.Lock()
	defer mu.Unlock()

	unlock.Guard(&mu, func() {
		time.Sleep(time.Second)
	})
}

func ExampleTagLock() {
	type countLocked struct{}

	var (
		mu    lock.TagMutex[countLocked]
		count int
	)

	incrementWithLock := func(l countLocked) {
		count++
	}

	readWithLock := func(l countLocked) int {
		return count
	}

	lock.GuardTag(&mu, func(l countLocked) {
		incrementWithLock(l)
	})

	n := lock.GuardTagged(&mu, func(l countLocked) int {
		return readWithLock(l)
	})
	fmt.Println(n)
}

Documentation

Overview

Package lock provides locking helpers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Guard

func Guard(lock sync.Locker, f func())

Guard invokes f while keeping the lock locked.

Example
package main

import (
	"fmt"
	"sync"

	"import.name/lock"
)

func main() {
	var (
		mu    sync.Mutex
		count int
	)

	lock.Guard(&mu, func() {
		count++
	})

	n := lock.Guarded(&mu, func() int {
		return count
	})
	fmt.Println(n)
}
Output:

func GuardTag added in v1.1.0

func GuardTag[Tag any](ock TagLocker[Tag], f func(Tag))

func GuardTagged added in v1.1.0

func GuardTagged[Tag any, Val any](lock TagLocker[Tag], f func(Tag) Val) Val

func Guarded

func Guarded[T any](lock sync.Locker, f func() T) T

Guarded invokes f while keeping the lock locked. The return value is passed through.

Types

type TagLocker added in v1.1.0

type TagLocker[Tag any] interface {
	Lock() Tag
	Unlock()
}

type TagMutex added in v1.1.0

type TagMutex[Tag any] struct {
	sync.Mutex
}
Example
package main

import (
	"fmt"

	"import.name/lock"
)

func main() {
	type countLocked struct{}

	var (
		mu    lock.TagMutex[countLocked]
		count int
	)

	incrementWithLock := func(l countLocked) {
		count++
	}

	readWithLock := func(l countLocked) int {
		return count
	}

	lock.GuardTag(&mu, func(l countLocked) {
		incrementWithLock(l)
	})

	n := lock.GuardTagged(&mu, func(l countLocked) int {
		return readWithLock(l)
	})
	fmt.Println(n)
}
Output:

func (*TagMutex[Tag]) Lock added in v1.1.0

func (mu *TagMutex[Tag]) Lock() Tag

Directories

Path Synopsis
Package unlock provides unlocking helpers.
Package unlock provides unlocking helpers.

Jump to

Keyboard shortcuts

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