OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #ifndef BASE_SYNCHRONIZATION_SEQLOCK_H_ | |
6 #define BASE_SYNCHRONIZATION_SEQLOCK_H_ | |
7 #pragma once | |
8 | |
9 #include "base/base_export.h" | |
10 #include "base/atomicops.h" | |
11 | |
12 namespace base { | |
13 | |
14 // This SeqLock handles only *one* writer and multiple readers. It may be | |
15 // suitable for low-contention with relatively infrequent writes, and many | |
16 // readers. See: | |
17 // http://en.wikipedia.org/wiki/Seqlock | |
18 // http://www.concurrencykit.org/doc/ck_sequence.html | |
19 class BASE_EXPORT SeqLock { | |
20 public: | |
21 SeqLock() : sequence_(0) {} | |
22 | |
23 subtle::Atomic32 ReadBegin() { | |
24 base::subtle::Atomic32 version; | |
25 for (;;) { | |
26 version = subtle::Acquire_Load(&sequence_); | |
27 | |
28 // If the a sequence is even, then the associated data may be in a | |
29 // consistent state. | |
30 if ((version & 1) == 0) | |
31 break; | |
32 | |
33 // Otherwise, a thread is in the middle of an update. Retry the read. | |
34 PlatformThread::YieldCurrentThread(); | |
35 } | |
36 return version; | |
37 } | |
38 | |
39 bool ReadRetry(subtle::Atomic32 version) { | |
40 // If the sequence number was updated then a read should be re-attempted. | |
41 // -- Load fence, read membarrier | |
42 bool ret = subtle::Release_Load(&sequence_) != version; | |
43 return ret; | |
44 } | |
45 | |
46 void WriteBegin() { | |
47 // Increment the sequence number to odd to indicate the beginning of a | |
48 // write update. | |
49 subtle::Barrier_AtomicIncrement(&sequence_, 1); | |
jbates
2011/11/29 00:05:26
I'm not sure why there's BarrierAtomicIncrement an
| |
50 // -- Store fence, write membarrier | |
51 } | |
52 | |
53 void WriteEnd() { | |
54 // Increment the sequence to an even number to indicate the completion of | |
55 // a write update. | |
56 // -- Store fence, write membarrier | |
57 subtle::Barrier_AtomicIncrement(&sequence_, 1); | |
jbates
2011/11/29 00:05:26
And this:
subtle::Release_Store(&sequence_, sequen
| |
58 } | |
59 | |
60 private: | |
61 base::subtle::Atomic32 sequence_; | |
62 DISALLOW_COPY_AND_ASSIGN(SeqLock); | |
63 }; | |
64 | |
65 } // namespace base | |
66 | |
67 #endif // BASE_SYNCHRONIZATION_SEQLOCK_H_ | |
OLD | NEW |