本文主要是介绍《C++ Concurrency in Action》笔记4 vectorthread,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
将多个thread对象放到vector中,之后顺序执行join。看如下示例:
vector<int> v_id(20);
void f(int i)
{v_id[i] = i;
}
void call_by_main()
{vector<thread> v;for (int i = 0; i < 20; ++i){v.push_back(thread(f,i));}for_each(v.begin(), v.end(), mem_fn(&thread::join));for_each(v_id.begin(), v_id.end(), [](int i) {cout << i << endl; });system("pause");
}
执行结果:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
请按任意键继续. . .
此示例中多个线程单独访问一个全局vector,没有加锁,暂时认为没有问题,如果以后发现问题再更正。
这篇关于《C++ Concurrency in Action》笔记4 vectorthread的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!