Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

example

https://stackoverflow.com/questions/244316/reader-writer-locks-in-c
Since C++ 17 (VS2015) you can use the standard:

#include <shared_mutex>

typedef std::shared_mutex Lock;
typedef std::unique_lock<Lock>  WriteLock;
typedef std::shared_lock<Lock>  ReadLock;

Lock myLock;

void ReadFunction()
{
     ReadLock r_lock(myLock);
     //Do reader stuff
}

void WriteFunction()
{
     WriteLock w_lock(myLock);
     //Do writer stuff
}

std::shared_mutex

If one thread has acquired the exclusive lock (through lock, try_lock), no other threads can acquire the lock (including the shared).

If one thread has acquired the shared lock (through lock_shared, try_lock_shared), no other thread can acquire the exclusive lock, but can acquire the shared lock.

Only when the exclusive lock has not been acquired by any thread, the shared lock can be acquired by multiple threads.

Within one thread, only one lock (shared or exclusive) can be acquired at the same time.

Shared mutexes are especially useful when shared data can be safely read by any number of threads simultaneously, but a thread may only write the same data when no other thread is reading or writing at the same time.

std::shared_lock

shared mutex ownership wrapper
Locking a shared_lock locks the associated shared mutex in shared mode (to lock it in exclusive mode, std::unique_lock can be used)

std::unique_lock

mutex ownership wrapper

评论