-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
65 lines (57 loc) · 1.35 KB
/
sync.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package gost
import "sync"
// A mutual exclusion lock.
//
// locker := MutexNew[ISize](0)
// ptr := locker.Lock()
// *ptr = 1
// locker.Unlock()
type Mutex[T any] struct {
value *T
lock sync.Mutex
}
func MutexNew[T any](value T) Mutex[T] {
return Mutex[T]{
value: &value,
lock: sync.Mutex{},
}
}
// Acquires a mutex, blocking the current thread until it is able to do so.
//
// locker := MutexNew[ISize](0)
// ptr := locker.Lock()
// *ptr = 1
func (self *Mutex[T]) Lock() *T {
self.lock.Lock()
return self.value
}
// Immediately drops the guard, and consequently unlocks the mutex.
//
// locker := MutexNew[ISize](0)
// ptr := locker.Lock()
// *ptr = 1
// locker.Unlock()
func (self *Mutex[T]) Unlock() {
self.lock.Unlock()
}
// An error returned by TryLock.
type TryLockError struct{}
func (self TryLockError) Error() string {
return "Mutex is locked"
}
// Attempts to acquire this lock.
// If the lock could not be acquired at this time, then Err is returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.
//
// locker := MutexNew[ISize](0)
// ptr := locker.TryLock()
// if ptr.IsErr() {
// panic("Mutex is locked")
// }
// *ptr.Unwrap() = 1
func (self *Mutex[T]) TryLock() Result[*T] {
if self.lock.TryLock() {
return Ok[*T](self.value)
} else {
return Err[*T](TryLockError{})
}
}