我有一个这样的程序。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
template<int Thread>
void run()
{
for(int j=0;j<5;++j)
{
static std::mutex m;
m.lock();
cout<<"Thread "<<Thread<<" running... "<<j<<endl;
m.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main(int argc , char * argv [])
{
std::thread t1(run<1>);
std::thread t2(run<2>);
t1.join();
t2.join();
return 0;
}
有一个静态互斥锁,run()
以确保cout
将被独占执行。但是,当我使用 Visual Studio 2012 运行该程序时,输出为:
Thread Thread 2 running... 01
running... 0
Thread 1 running... 1
Thread 2 running... 1
Thread 1 running... 2
Thread 2 running... 2
Thread 2 running... 3
Thread 1 running... 3
Thread 1 running... 4
Thread 2 running... 4
看起来互斥锁在run()
. 我的程序有什么问题吗?