一、锁
std::scoped_lock和unique_lock 是一个互斥包装类,它提供了获取和释放锁的 RAII 样式方法。 这意味着,当对象被构造时,锁被获取,当对象被破坏时,锁被释放。
shared_lock是read lock。被锁后仍允许其他线程执行同样被shared_lock的代码。这是一般做读操作时的需要。共享锁,也叫多线程锁,当data被线程A读取时,仍允许其它线程读取data,但是不能写入。
unique_lock是write lock。被锁后不允许其他线程执行被shared_lock或unique_lock的代码。在写操作时,一般用这个,可以同时限制unique_lock的写和share_lock的读。独占锁,也叫单线程锁,仅允许单个线程访问,该线程访问结束后,其它线程才可以访问,避免输入写入冲突。即,当data被线程A写入时,其它线程既不能读取,也不能写入。
二、代码
// This program provides a small example of the use of std::scoped_lock.
// std::scoped_lock is a mutex wrapper class that provides a RAII-style
// method of obtaining and releasing locks. This means that when the object
// is constructed, the locks are acquired, and when the object is destructed,
// the locks are released.
// 本程序提供了使用 std::scoped_lock 的小示例。
// std::scoped_lock 是一个互斥包