C++ 读写锁

需要 boost 库支持,或者 C++ 17 原生支持 std::shared_mutex

#include 
#include 
using namespace std;
typedef boost::shared_mutex             SharedMutex;
typedef boost::unique_lock  WriteLock;
typedef boost::shared_lock  ReadLock;


int main() {
    int count = 0;
    SharedMutex _mutex;
    {
        WriteLock lock(_mutex);
        // 双写必阻塞,可以写线程验证
        // WriteLock lock(_mutex);
        count++;
    }
    {
        WriteLock lock(_mutex);
        // 一读一写也会阻塞
        // ReadLock lock1(_mutex);
        count++;
    }
    {
        // 读是可以重入的
        ReadLock lock1(_mutex);
        ReadLock lock2(_mutex);
        ReadLock lock3(_mutex);
        count++;
    }
    cout << count;
    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)