我正在学习std::mutex
,std::thread
我对以下 2 段代码的不同行为感到惊讶:
#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;
}
输出是顺序的。但是如果我不命名变量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;
}
在第二种情况下似乎std::lock_guard
没有用,为什么?