#include <iostream>
#include <mutex>
#include <thread>
std::mutex coutMutex;
int main(){
std::thread t([]{
std::cout << "Still waiting ..." << std::endl;
std::lock_guard<std::mutex> lockGuard(coutMutex);
std::cout << std::this_thread::get_id() << std::endl;
}
);
{
std::lock_guard<std::mutex> lockGuard(coutMutex);
std::cout << std::this_thread::get_id() << std::endl;
t.join();
}
}
lock_guard 相当于 lock 和 unlock,在代码段结束或者函数结束时unlock,因此在主线程中已经对 std::cout 流进行了加锁,在代码段输出 “Still Waiting” 后,尝试对std::cout 进行加锁时,会导致失败,等待资源。
改进措施:
{
t.join();
std::lock_guard<std::mutex> lockGuard(coutMutex);
std::cout << std::this_thread::get_id() << std::endl;
}
{
{
std::lock_guard<std::mutex> lockGuard(coutMutex);
std::cout << std::this_thread::get_id() << std::endl;
}
t.join();
}
英文博客地址 : https://www.modernescpp.com/index.php/prefer-locks-to-mutexes
lock_guard 和 unique_guard 的讲解:https://www.jianshu.com/p/34d219380d90
原文地址:https://www.cnblogs.com/walnuttree/p/10690025.html
时间: 2024-10-20 04:59:41