C++ stl锁的使用

发布时间 2023-07-22 16:05:47作者: Arthurian

我们在日常开发中经常要用到锁,这里记录一下实际开发过程中stl提供的锁的使用。

1、读写锁

读写锁算是用到的比较多的一种类型,主要实现对于同一个共享数据区,一个时间点只能有一个线程进行写(增删改),但可以有多个线程同时读(查)。换句话说,当有一个线程写的时候,其他线程(不管是读线程还是写线程)都必须等待;而有一个线程读的时候,其他的读线程也可以读,但是写线程要等待。

当前在实现读写锁用到了 shared_mutex、shared_lock 和 unique_lock,示例代码如下:

 1 // 作为共享数据区
 2 std::map<int, int> g_mapTest;
 3 
 4 // 创建一个读写锁对象
 5 std::shared_mutex mtx;
 6 
 7 // 获取map里面key为iKey的值
 8 void ReadThread(int iKey)
 9 {
10     std::shared_lock<std::shared_mutex> lock(mtx);
11     auto iter = g_mapTest.find(iKey);
12     if(g_mapTest.end() == iter)
13     {
14         return;
15     }
16     
17     //do something
18 }
19 
20 // 更新map里面key是iKey的值为iVal
21 void WriteThread(int iKey, int iVal)
22 {
23     std::unique_lock<std::shared_mutex> lock(mtx);
24     g_mapTest[iKey] = iVal;
25 }

 

这里假设有多个 ReadThread 和多个 WriteThread,那么每次 WriteThread 执行的时候,其他线程进来都会阻塞在 lock 的位置;而 ReadThread 执行的时候,其他的 ReadThread 也是可以执行的,而不被阻塞的,但是其他的 WriteThread 是被阻塞的。