-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_trylock_test.go
64 lines (47 loc) · 1.2 KB
/
example_trylock_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
54
55
56
57
58
59
60
61
62
63
64
package mogul_test
import (
"fmt"
"math/rand"
"sync"
"time"
"github.com/ReneKroon/mogul"
"github.com/globalsign/mgo"
)
var database = "mogul"
var collection = "locks"
var tasks = "tasks"
func ExampleManager_TryLock() {
session := initDB()
defer clearDB(session)
var m mogul.MutexCreator = mogul.New(session.DB(database).C(collection), session.DB(database).C(tasks))
var wg sync.WaitGroup
hits := 0
// Lets started some goroutines that sleep for a while and then try to increment a counter.
// If the lock is acquired by one routine, the others will fail and not increment.
for i := 1; i <= 10; i++ {
wg.Add(1)
user := fmt.Sprintf("User#%d", i)
go func() {
time.Sleep(time.Microsecond * time.Duration(rand.Float32()*10000))
l := m.NewMutex("Multiple", user)
if got, _ := l.TryLock(time.Hour); got {
hits++
}
wg.Done()
}()
}
wg.Wait()
fmt.Println(hits)
}
func initDB() *mgo.Session {
uri := "mongodb://localhost/"
s, _ := mgo.Dial(uri)
s.SetSafe(&mgo.Safe{FSync: true})
s.DB(database).C(collection).DropCollection()
return s
}
func clearDB(s *mgo.Session) {
s.DB(database).C(collection).DropCollection()
s.DB(database).C(tasks).DropCollection()
s.Close()
}