Reader/Writer Locks in C++

2019-01-02 20:13发布

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.

12条回答
牵手、夕阳
2楼-- · 2019-01-02 20:42

Boost.Thread has since release 1.35.0 already supports reader-writer locks. The good thing about this is that the implementation is greatly cross-platform, peer-reviewed, and is actually a reference implementation for the upcoming C++0x standard.

查看更多
谁念西风独自凉
3楼-- · 2019-01-02 20:44

Intel Thread Building Blocks also provide a couple of rw_lock variants:

http://www.threadingbuildingblocks.org/

They have a spin_rw_mutex for very short periods of contention and a queueing_rw_mutex for longer periods of contention. The former can be used in particularly performance sensitive code. The latter is more comparable in performance to that provided by Boost.Thread or directly using pthreads. But profile to make sure which one is a win for your access patterns.

查看更多
看风景的人
4楼-- · 2019-01-02 20:51

Newer versions of boost::thread have read/write locks (1.35.0 and later, apparently the previous versions did not work correctly).

They have the names shared_lock, unique_lock, and upgrade_lock and operate on a shared_mutex.

查看更多
大哥的爱人
5楼-- · 2019-01-02 20:51

Edit: The MSDN Magazine link isn't available anymore. The CodeProject article is now available on https://www.codeproject.com/Articles/32685/Testing-reader-writer-locks and sums it up pretty nicely. Also I found a new MSDN link about Compound Synchronisation Objects.

There is an article about reader-writer locks on MSDN that presents some implementations of them. It also introduces the Slim reader/writer lock, a kernel synchronisation primitive introduced with Vista. There's also a CodeProject article about comparing different implementations (including the MSDN article's ones).

查看更多
残风、尘缘若梦
6楼-- · 2019-01-02 20:52

You could copy Sun's excellent ReentrantReadWriteLock. It includes features such as optional fairness, lock downgrading, and of course reentrancy.

Yes it's in Java, but you can easily read and transpose it to C++, even if you don't know any Java. The documentation I linked to contains all the behavioral properties of this implementation so you can make sure it does what you want.

If nothing else, it's a guide.

查看更多
美炸的是我
7楼-- · 2019-01-02 20:53

Multiple-Reader, Single-Writer Synchronization Lock Class for Win32 by Glenn Slayde

http://www.glennslayden.com/code/win32/reader-writer-lock

查看更多
登录 后发表回答