1/*
2
3 This Source Code Form is subject to the terms of the Mozilla Public
4 License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 Copyright (c) 2013, Armon Dadgar armon.dadgar@gmail.com
8 Copyright (c) 2013, Mitchell Hashimoto mitchell.hashimoto@gmail.com
9
10 Alternatively, the contents of this file may be used under the terms
11 of the GNU General Public License Version 3 or later, as described below:
12
13 This file is free software: you may copy, redistribute and/or modify
14 it under the terms of the GNU General Public License as published by the
15 Free Software Foundation, either version 3 of the License, or (at your
16 option) any later version.
17
18 This file is distributed in the hope that it will be useful, but
19 WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
21 Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program. If not, see http://www.gnu.org/licenses/.
25
26*/
27
28package util
29
30import (
31 "sync/atomic"
32)
33
34// LamportClock is a thread safe implementation of a lamport clock. It
35// uses efficient atomic operations for all of its functions, falling back
36// to a heavy lock only if there are enough CAS failures.
37type LamportClock struct {
38 counter uint64
39}
40
41// LamportTime is the value of a LamportClock.
42type LamportTime uint64
43
44func NewLamportClock() LamportClock {
45 return LamportClock{
46 counter: 1,
47 }
48}
49
50func NewLamportClockWithTime(time uint64) LamportClock {
51 return LamportClock{
52 counter: time,
53 }
54}
55
56// Time is used to return the current value of the lamport clock
57func (l *LamportClock) Time() LamportTime {
58 return LamportTime(atomic.LoadUint64(&l.counter))
59}
60
61// Increment is used to increment and return the value of the lamport clock
62func (l *LamportClock) Increment() LamportTime {
63 return LamportTime(atomic.AddUint64(&l.counter, 1))
64}
65
66// Witness is called to update our local clock if necessary after
67// witnessing a clock value received from another process
68func (l *LamportClock) Witness(v LamportTime) {
69WITNESS:
70 // If the other value is old, we do not need to do anything
71 cur := atomic.LoadUint64(&l.counter)
72 other := uint64(v)
73 if other < cur {
74 return
75 }
76
77 // Ensure that our local clock is at least one ahead.
78 if !atomic.CompareAndSwapUint64(&l.counter, cur, other+1) {
79 // CAS: CompareAndSwap
80 // The CAS failed, so we just retry. Eventually our CAS should
81 // succeed or a future witness will pass us by and our witness
82 // will end.
83 goto WITNESS
84 }
85}