c++11 std::unique_lock

std::unique_lock

  • 用法类似lock_guard,离开作用域后自动unlock
  • 定义的时候可以不需要mutex初始化,可以为空
  • 可以手动调用lock(),unlock()
// unique_lock example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock
#include <chrono>
using namespace std;
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; }
  // lck.unlock(); // 可以手动释放锁
  // lck.lock();   // 可以再次加锁
  std::this_thread::sleep_for(1s);
  std::cout << '\n';
}

void UniqueLockTest()
{
  std::thread th1 (print_block,50,'*');
  std::thread th2 (print_block,50,'$');

  th1.join();
  th2.join();
}

参考

https://en.cppreference.com/w/cpp/thread/unique_lock
https://cplusplus.com/reference/mutex/unique_lock/

posted @ 2023-08-02 21:00  BuzzWeek  阅读(103)  评论(0编辑  收藏  举报