-
Notifications
You must be signed in to change notification settings - Fork 0
/
atomic_worker.go
58 lines (48 loc) · 1.09 KB
/
atomic_worker.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
package snowflake
import (
"runtime"
"sync/atomic"
)
// AtomicWorker snowflake worker implemented by package sync/atomic
type AtomicWorker struct {
workerID int64
lastTime int64
lastSeq int64
}
// NewAtomicWorker create a new AtomicWorker object
func NewAtomicWorker(workerID int64) (Worker, error) {
if err := checkWorkerID(workerID); err != nil {
return nil, err
}
return &AtomicWorker{
workerID: workerID,
lastTime: -1,
lastSeq: -1,
}, nil
}
// Next get next ID
func (aw *AtomicWorker) Next() (int64, error) {
var lastTime, lastSeq int64
var seq, now int64
for {
seq, now = 0, nowMillis()
lastTime = atomic.LoadInt64(&aw.lastTime)
if lastTime > now {
continue
}
lastSeq = atomic.LoadInt64(&aw.lastSeq)
if now == lastTime {
seq = sequenceMask & (lastSeq + 1)
if seq == 0 {
// reach to max sequence, wait
now = waitUntilNextMillis(now)
}
}
if !atomic.CompareAndSwapInt64(&aw.lastTime, lastTime, now) ||
!atomic.CompareAndSwapInt64(&aw.lastSeq, lastSeq, seq) {
runtime.Gosched()
continue
}
return combine(now, aw.workerID, seq), nil
}
}