一、锁
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 是一个互斥包装类,它提供了获取和释放锁的 RAII 样式方法。
// 这意味着,当对象被构造时,锁被获取,当对象被破坏时,锁被释放。
// Includes std::cout (printing) for demo purposes.
#include <iostream>
// Includes the mutex library header.
#include <mutex>
// Includes the thread library header.
#include <thread>
// Defining a global count variable and two mutexes to be used by both threads.
int count = 0;
std::mutex m;
// The add_count function allows for a thread to increment the count variable
// by 1, atomically.
void add_count() {
// The constructor of std::scoped_lock allows for the thread to acquire the
// mutex m.
// shared_lock是read lock。被锁后仍允许其他线程执行同样被shared_lock的代码。这是一般做读操作时的需要。
//共享锁,也叫多线程锁,当data被线程A读取时,仍允许其它线程读取data,但是不能写入。
std::scoped_lock slk(m);
count += 1;
// 函数开始获取锁,函数结束自动释放锁
// Once the function add_count finishes, the object slk is out of scope, and
// in its destructor, the mutex m is released.
}
void add_count2() {
// The constructor of std::scoped_lock allows for the thread to acquire the
// mutex m.
// unique_lock是write lock。被锁后不允许其他线程执行被shared_lock或unique_lock的代码。
// 在写操作时,一般用这个,可以同时限制unique_lock的写和share_lock的读。
// 独占锁,也叫单线程锁,仅允许单个线程访问,该线程访问结束后,其它线程才可以访问,避免输入写入冲突。
// 即,当data被线程A写入时,其它线程既不能读取,也不能写入。
std::unique_lock ulk(m);
// 函数开始获取锁,函数结束自动释放锁
count += 1;
// Once the function add_count finishes, the object slk is out of scope, and
// in its destructor, the mutex m is released.
}
// The main method is identical to the one in mutex.cpp. It constructs the
// thread objects, runs add_count on both threads, and prints the result of
// count after execution.
int main() {
std::thread t1(add_count);
std::thread t2(add_count);
t1.join();
t2.join();
std::thread t3(add_count2);
std::thread t4(add_count2);
t3.join();
t4.join();
std::cout << "Printing count: " << count << std::endl;
return 0;
}
三、运行结果

本文介绍了C++中的std::scoped_lock和unique_lock,它们作为互斥包装类,提供RAII风格的锁管理。scoped_lock用于读写操作,unique_lock则用于独占锁,确保线程安全。通过实例展示了如何在多线程环境中使用这些类来实现同步控制。
6429

被折叠的 条评论
为什么被折叠?



