共享锁,也叫读写锁,主要应用与读多写少的场景。
比如,在多线程环境下,多个线程操作同一个文件,其中读文件的操作比写文件的操作更加频繁,那么在进行读操作时,不需要互斥,线程间可以共享这些数据,随意的读取。但是一旦有写操作,那么一定要进行互斥操作,否则读取到的数据可能存在不一致。
C++14 共享超时互斥锁 shared_timed_mutex
读线程 调用 lock_shared()
获取共享锁,写线程 调用 lock()
获取互斥锁。
- 当调用lock()的时候,如果有线程获取了共享锁,那么写线程会等待,直到所有线程将数据读取完成释放共享锁,再去锁定资源,进行修改;
- 当调用lock_shared()时,如果有写线程获取了互斥锁,那么需要等待
- 当调用lock_shared()时,如果有读线程获取共享锁,也会直接返回,获取成功。
代码示例:
std::shared_timed_mutex stmtx;
void ReadThread()
{
while (true)
{
stmtx.lock_shared();
std::cout << "thread id = " << std::this_thread::get_id() << " lock shared read" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
stmtx.unlock_shared();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void WriteThread()
{
while (true)
{
stmtx.lock();
std::cout << "thread id = " << std::this_thread::get_id() << " lock write" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
stmtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main()
{
for(int i = 0; i < 3; ++i)
{
std::thread t(ReadThread);
t.detach();
}
for(int i = 0; i < 2; ++i)
{
std::thread t(WriteThread);
t.detach();
}
getchar();
return 0;
}
执行结果:
thread id = 139663449360128 lock write
thread id = 139663457752832 lock shared read
thread id = 139663474538240 lock shared read
thread id = 139663466145536 lock shared read
thread id = 139663440967424 lock write
thread id = 139663474538240 lock shared read
thread id = 139663466145536 lock shared read
thread id = 139663457752832 lock shared read
thread id = 139663449360128 lock write
thread id = 139663457752832 lock shared read
thread id = 139663466145536 lock shared read
thread id = 139663474538240 lock shared read
thread id = 139663440967424 lock write
thread id = 139663466145536 lock shared read
thread id = 139663457752832 lock shared read
thread id = 139663474538240 lock shared read
thread id = 139663449360128 lock write
thread id = 139663457752832 lock shared read
thread id = 139663466145536 lock shared read
thread id = 139663474538240 lock shared read
thread id = 139663440967424 lock write
thread id = 139663457752832 lock shared read
thread id = 139663466145536 lock shared read
thread id = 139663474538240 lock shared read
C++17 共享互斥 shared_mutex
shared_mutex与shared_timed_mutex基本一致,shared_timed_mutex较shared_mutex多了一些与时间相关的接口,如:
try_lock_for(...);
try_lock_shared_for(...);
try_lock_shared_until(...);
try_lock_until(...);
用法和共享超时互斥锁一致,如
std::shared_mutex smtx;
smtx.lock_shared();
smtx.unlock_shared();
smtx.lock();
smtx.unlock();