I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- What is the best way to create a lock from a web a
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Difference between Thread#run and Thread#wakeup?
- Selecting only the first few characters in a strin
- Java/Spring MVC: provide request context to child
You can use boost to create a read-write lock:
Whatever you decide to use, benchmark your work load against simple locks, as read/write locks tend to be 3-40x slower than simple mutex, when there is no contention.
Here is some reference
Using standard pre-tested, pre-built stuff is always good (for example, Boost as another answer suggested), but this is something that's not too hard to build yourself. Here's a dumb little implementation pulled out from a project of mine:
pthreads
not really being Windows-native, but the general idea is here. This implementation is slightly biased towards writers (a horde of writers can starve readers indefinitely); just modifywriter_unlock
if you'd rather the balance be the other way around.Yes, this is C and not C++. Translation is an exercise left to the reader.
Edit
Greg Rogers pointed out that the POSIX standard does specify
pthread_rwlock_*
. This doesn't help if you don't havepthreads
, but it stirred my mind into remembering: Pthreads-w32 should work! Instead of porting this code to non-pthreads
for your own use, just use Pthreads-w32 on Windows, and nativepthreads
everywhere else.I can recommend the ACE library, which provides a multitude of locking mechanisms and is ported to various platforms.
Depending on the boundary conditions of your problem, you may find the following classes useful:
ACE_RW_Process_Mutex
ACE_Write_Guard
andACE_Read_Guard
ACE_Condition
http://www.codeproject.com/KB/threads/ReaderWriterLock.aspx
Here is a good and lightweight implementation suitable for most tasks.
C++17 supports
std::shared_mutex
. It is supported in MSVC++ 2015 and 2017.