rsy*_*640 6 c++ c++11 stdthread stdmutex
我正在学习std::mutex,std::thread我对下面两段代码的不同行为感到惊讶:
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
std::mutex mtx;
void foo(int k)
{
std::lock_guard<std::mutex> lg{ mtx };
for (int i = 0; i < 10; ++i)
cout << "This is a test!" << i << endl;
cout << "The test " << k << " has been finished." << endl;
}
int main()
{
std::thread t1(foo, 1);
std::thread t2(foo, 2);
t1.join();
t2.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是顺序的.但如果我没有名称变量std::lock_guard<std::mutex>,则输出无序
void foo(int k)
{
std::lock_guard<std::mutex> { mtx }; // just erase the name of variable
for (int i = 0; i < 10; ++i)
cout << "This is a test!" << i << endl;
cout << "The test " << k << " has been finished." << endl;
}
Run Code Online (Sandbox Code Playgroud)
好像std::lock_guard第二种情况似乎没用,为什么?
lub*_*bgr 16
这个宣言
std::lock_guard<std::mutex> { mtx };
Run Code Online (Sandbox Code Playgroud)
不会将创建的对象绑定到名称,它是仅存在于此特定语句的临时变量.与此相反,具有名称并在堆栈上创建的变量将一直存在,直到创建它的作用域结束.
在此CppCon演讲中(从31:42开始),演示者列出了std::lock_guard未绑定到局部变量的临时实例的创建,作为Facebook代码库中的常见错误.
| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |