-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexample_test.go
53 lines (43 loc) · 1.22 KB
/
example_test.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
package lock_test
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/viney-shih/go-lock"
)
func ExampleCASMutex() {
// set RWMutex with CAS mechanism (CASMutex).
var rwMut lock.RWMutex = lock.NewCASMutex()
// set default value
count := int32(0)
// block here
rwMut.Lock()
go func() {
time.Sleep(50 * time.Millisecond)
fmt.Println("Now is", atomic.AddInt32(&count, 1)) // Now is 1
rwMut.Unlock()
}()
// waiting for previous goroutine releasing the lock, and locking it again
rwMut.Lock()
fmt.Println("Now is", atomic.AddInt32(&count, 2)) // Now is 3
// TryLock without blocking
// Return false, because the lock is not released.
fmt.Println("Return", rwMut.TryLock())
// RTryLockWithTimeout without blocking
// Return false, because the lock is not released.
fmt.Println("Return", rwMut.RTryLockWithTimeout(50*time.Millisecond))
// TryLockWithContext without blocking
ctx, cancel := context.WithTimeout(context.TODO(), 50*time.Millisecond)
defer cancel()
// Return false, because the lock is not released.
fmt.Println("Return", rwMut.TryLockWithContext(ctx))
// release the lock in the end.
rwMut.Unlock()
// Output:
// Now is 1
// Now is 3
// Return false
// Return false
// Return false
}