mem_clock.go

 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
34var _ Clock = &MemClock{}
35
36// MemClock is a thread safe implementation of a lamport clock. It
37// uses efficient atomic operations for all of its functions, falling back
38// to a heavy lock only if there are enough CAS failures.
39type MemClock struct {
40	counter uint64
41}
42
43// NewMemClock create a new clock with the value 1.
44// Value 0 is considered as invalid.
45func NewMemClock() *MemClock {
46	return &MemClock{
47		counter: 1,
48	}
49}
50
51// NewMemClockWithTime create a new clock with a value.
52func NewMemClockWithTime(time uint64) *MemClock {
53	return &MemClock{
54		counter: time,
55	}
56}
57
58// Time is used to return the current value of the lamport clock
59func (mc *MemClock) Time() Time {
60	return Time(atomic.LoadUint64(&mc.counter))
61}
62
63// Increment is used to return the value of the lamport clock and increment it afterwards
64func (mc *MemClock) Increment() (Time, error) {
65	return Time(atomic.AddUint64(&mc.counter, 1) - 1), nil
66}
67
68// Witness is called to update our local clock if necessary after
69// witnessing a clock value received from another process
70func (mc *MemClock) Witness(v Time) error {
71WITNESS:
72	// If the other value is old, we do not need to do anything
73	cur := atomic.LoadUint64(&mc.counter)
74	other := uint64(v)
75	if other < cur {
76		return nil
77	}
78
79	// Ensure that our local clock is at least one ahead.
80	if !atomic.CompareAndSwapUint64(&mc.counter, cur, other+1) {
81		// CAS: CompareAndSwap
82		// The CAS failed, so we just retry. Eventually our CAS should
83		// succeed or a future witness will pass us by and our witness
84		// will end.
85		goto WITNESS
86	}
87
88	return nil
89}