]> git.ipfire.org Git - thirdparty/squid.git/blob - src/ipc/ReadWriteLock.h
Merge from trunk
[thirdparty/squid.git] / src / ipc / ReadWriteLock.h
1 /*
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 #ifndef SQUID_IPC_READ_WRITE_LOCK_H
10 #define SQUID_IPC_READ_WRITE_LOCK_H
11
12 #include "ipc/AtomicWord.h"
13
14 class StoreEntry;
15
16 namespace Ipc
17 {
18
19 class ReadWriteLockStats;
20
21 /// an atomic readers-writer or shared-exclusive lock suitable for maps/tables
22 /// Also supports reading-while-appending mode when readers and writer are
23 /// allowed to access the same locked object because the writer promisses
24 /// to only append new data and all size-related object properties are atomic.
25 class ReadWriteLock
26 {
27 public:
28 // default constructor is OK because of shared memory zero-initialization
29
30 bool lockShared(); ///< lock for reading or return false
31 bool lockExclusive(); ///< lock for modification or return false
32 void unlockShared(); ///< undo successful sharedLock()
33 void unlockExclusive(); ///< undo successful exclusiveLock()
34 void switchExclusiveToShared(); ///< stop writing, start reading
35
36 void startAppending(); ///< writer keeps its lock but also allows reading
37
38 /// adds approximate current stats to the supplied ones
39 void updateStats(ReadWriteLockStats &stats) const;
40
41 public:
42 mutable Atomic::Word readers; ///< number of reading users
43 Atomic::Word writing; ///< there is a writing user (there can be at most 1)
44 Atomic::Word appending; ///< the writer has promissed to only append
45
46 private:
47 mutable Atomic::Word readLevel; ///< number of users reading (or trying to)
48 Atomic::Word writeLevel; ///< number of users writing (or trying to write)
49 };
50
51 /// approximate stats of a set of ReadWriteLocks
52 class ReadWriteLockStats
53 {
54 public:
55 ReadWriteLockStats();
56
57 void dump(StoreEntry &e) const;
58
59 int count; ///< the total number of locks
60 int readable; ///< number of locks locked for reading
61 int writeable; ///< number of locks locked for writing
62 int idle; ///< number of unlocked locks
63 int readers; ///< sum of lock.readers
64 int writers; ///< sum of lock.writers
65 int appenders; ///< number of appending writers
66 };
67
68 } // namespace Ipc
69
70 #endif /* SQUID_IPC_READ_WRITE_LOCK_H */
71