#include <iostream>
#include <thread>
using namespace std;
void call(int tid)
{
cout << "Launched by thread " << tid << endl;
}
int main()
{
thread t[10];//启动一组线程
for(int i=0;i<10;i++)
{
t[i]=thread(call,i);
}
for(int i=0;i<10;i++)
{
t[i].join();
}
return 0;
}
能看到上面的结果中,程序一旦创建一条线程,其运行存在顺序不确定的现象。程序员的任务就是要确保这组线程在访问公共数据时不要出现阻塞。最后几行,所显示的错乱输出,甚至是会输出些混乱的字符。原因在于,程序内的11条线程都在竞争性地使用stdout这个公共资源,要避免上面的问题,可以在代码中使用拦截器(barriers),如std:mutex,以同步(synchronize)的方式来使得一群线程访问公共资源,或者,如果可行的话,为线程们预留下私用的数据结构,避免使用公共资源。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
std::mutex m;
void call(int tid)
{
m.lock();
cout << "Launched by thread " << tid << endl;
m.unlock();
}
int main()
{
thread t[10];//启动一组线程
for(int i=0;i<10;i++)
{
t[i]=thread(call,i);
}
for(int i=0;i<10;i++)
{
t[i].join();
}
return 0;
}