/*
与Mutex RAII相关,方便线程上锁,相比std::lock_guard提供了更好的上锁解锁控制,反正我是没看出来
也是在构造时上锁,在析构时解锁,感觉和lock_gurad大差不差
都是在线程函数中定义这样一个变量,利用其局部变量自动析构来解锁的特性
*/
#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; }
同样的问题:这个也是顺序执行的。

 

相关文章:

  • 2021-08-21
  • 2021-12-14
  • 2021-09-30
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2021-10-04
猜你喜欢
  • 2021-12-28
  • 2022-12-23
  • 2021-04-29
  • 2021-08-25
  • 2021-09-06
  • 2022-01-10
  • 2021-07-18
相关资源
相似解决方案