这里只介绍std::lock_guard、std::unique_lock
- std::unique_lock被称为唯一锁或独占锁。与std::lock_guard相比,std::unique_lock允许在锁的生命周期内手动控制锁的锁定和解锁,而不仅仅是在构造函数和析构函数中自动进行。这使得std::unique_lock在更复杂的场景中更加有用,例如当需要在锁的持有期间进行条件变量等待时。
- std::lock_guard 通常被称为 锁定守卫(Lock Guard)或 范围锁(Scoped
Lock)。它的主要目的是确保在特定代码块(作用域)内,某个互斥量(mutex)总是被锁定,并在离开该作用域时自动解锁。这样可以防止由于忘记解锁而导致的线程安全问题。
std::lock_guard 示例
代码解读:当奇数的时候,抛出异常。锁自动解除(因为离开了作用域)
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard
#include <stdexcept> // std::logic_error
std::mutex mtx;
void print_even (int x) {
if (x%2==0) std::cout << x << " is even\n";
else throw (std::logic_error("not even"));
}
void print_thread_id (int id) {
try {
// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
std::lock_guard<std::mutex> lck (mtx);
print_even(id);
}
catch (std::logic_error&) {
std::cout << "[exception caught]\n";
}
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}
std::unique_lock 示例
代码解读:要么先打印50个*然后打印50个
。要么反之。总之保证
∗
和
。要么反之。总之保证*和
。要么反之。总之保证∗和的打印是连续的
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
std::mutex mtx; // mutex for critical section
void print_block (int n, char c) {
// critical section (exclusive access to std::cout signaled by lifetime of lck):
std::unique_lock<std::mutex> lck (mtx);
for (int i=0; i<n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
int main ()
{
std::thread th1 (print_block,50,'*');
std::thread th2 (print_block,50,'$');
th1.join();
th2.join();
return 0;
}