c++17 共享锁shared_mutex

shared_mutex

  • shared_mutex::lock()用法同mutex::lock()
  • shared_mutex::lock_shared()允许多线程同时进入临界区,只用用于只读场景,不然是线程不安全的
  • shared_mutex::lock_shared()与shared_mutex::lock()互斥,不能同时上锁
  • shared_mutex(const shared_mutex&) = delete;
  • shared_mutex& operator=(const shared_mutex&) = delete;
#include <shared_mutex>
#include <iostream>
#include <thread>
using namespace std;

shared_mutex m;
int share_counter{0};

void increment1(int target)
{
    for (int i = 0; i < target; i++)
    {
        m.lock();
        share_counter++;
        m.unlock();
    }
}

void increment2(int target)
{
    for (int i = 0; i < target; i++)
    {
        m.lock_shared();
        share_counter++;
        m.unlock_shared();
    }
}

using incre_fun = void(int);
void test_increment(int target, incre_fun fun)
{
    share_counter = 0;
    thread t1(fun, target);
    thread t2(fun, target);
    t1.join();
    t2.join();
    cout << "Count result: " << share_counter << endl;
}

void test_increment2(int target, incre_fun fun1, incre_fun fun2)
{
    share_counter = 0;
    thread t1(fun1, target);
    thread t2(fun2, target);
    t1.join();
    t2.join();
    cout << "Count result: " << share_counter << endl;
}

void SharedMutexTest()
{
    test_increment(1000000, increment1);              // Count result: 2000000
    test_increment(1000000, increment2);              // Count result: 1906613
    test_increment2(1000000, increment1, increment2); // Count result: 2000000
}

参考

https://en.cppreference.com/w/cpp/thread/shared_mutex

posted @ 2023-08-01 22:13  BuzzWeek  阅读(199)  评论(0编辑  收藏  举报