#include<mutex>
#include <stdlib.h>
#include<stdio.h>
#include <iostream>
#include <thread>
using namespace std;
mutex mtx;
void foo()
{
std::lock_guard<std::mutex> lck (mtx);//#1 同步线程顺序执行,可以在输出终端看到规则的打印信息。
for(int i = 0; i < 100; i++)
{
this_thread::sleep_for(std::chrono::milliseconds(1));//#2
cout << i << " ";
}
cout<< endl;
}
int main()
{
std::thread first (foo);
std::thread second (foo);
std::thread third (foo);
// synchronize threads:
first.join();
second.join();
third.join();
getchar();
return 0;
}
#1:封装的mutex。
#2:离散线程执行的时间,在终端打印过程中使其产生竞态。
一个简单的使用mutex进行线程同步的例子。