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 lamport
29
30import (
31 "sync/atomic"
32)
33
34// Clock 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 Clock struct {
38 counter uint64
39}
40
41// Time is the value of a Clock.
42type Time uint64
43
44// NewClock create a new clock with the value 1.
45// Value 0 is considered as invalid.
46func NewClock() Clock {
47 return Clock{
48 counter: 1,
49 }
50}
51
52// NewClockWithTime create a new clock with a value.
53func NewClockWithTime(time uint64) Clock {
54 return Clock{
55 counter: time,
56 }
57}
58
59// Time is used to return the current value of the lamport clock
60func (l *Clock) Time() Time {
61 return Time(atomic.LoadUint64(&l.counter))
62}
63
64// Increment is used to return the value of the lamport clock and increment it afterwards
65func (l *Clock) Increment() Time {
66 return Time(atomic.AddUint64(&l.counter, 1) - 1)
67}
68
69// Witness is called to update our local clock if necessary after
70// witnessing a clock value received from another process
71func (l *Clock) Witness(v Time) {
72WITNESS:
73 // If the other value is old, we do not need to do anything
74 cur := atomic.LoadUint64(&l.counter)
75 other := uint64(v)
76 if other < cur {
77 return
78 }
79
80 // Ensure that our local clock is at least one ahead.
81 if !atomic.CompareAndSwapUint64(&l.counter, cur, other+1) {
82 // CAS: CompareAndSwap
83 // The CAS failed, so we just retry. Eventually our CAS should
84 // succeed or a future witness will pass us by and our witness
85 // will end.
86 goto WITNESS
87 }
88}