请参阅下面的代码。
#include <iostream>
#include <thread>
#include <list>
#include <algorithm>
using namespace std;
// a global variable
std::list<int>myList;
void addToList(int max, int interval)
{
for (int i = 0; i < max; i++) {
if( (i % interval) == 0) myList.push_back(i);
}
}
void printList()
{
for (std::list<int>::iterator itr = myList.begin(), end_itr = myList.end(); itr != end_itr; ++itr )
{
cout << *itr << ",";
}
}
int main()
{
int max = 100;
std::thread t1(addToList, max, 1);
std::thread t2(addToList, max, 10);
std::thread t3(printList);
t1.join();
t2.join();
t3.join();
return 0;
}
线程t3(printList(未打印列表。空输出即将到来。是因为t3在列表中插入任何项目之前先执行吗?这是什么原因?
如果像这样启动线程,就无法保证其中哪一个将首先执行或完成。
您正在执行3个线程,它们有不同的任务要做:
- 前两个线程执行函数addToList,该函数具有用于n次的for
- 第三个线程正在执行函数printList
在这种情况下,printList不会等待t1和t2完成。在阅读列表时(t3*(**t1和t2尚未向列表添加任何内容。
t1
|-- loop[0 max]{ / calculate interval / adding number at the end of list} -->[End of t1]
t2
|-- loop[0 max]{ / calculate interval / adding number at the end of list} -->[End of t2]
t3
|-- Rd & Prnt -->[End of t3]
^ ^
| |
t3 finished before t1 and t2 Possible end of the threads t1 and t2 (*)
为了避免这种情况,t3必须等待t1和t2结束。
int main()
{
int max = 100;
std::thread t1(addToList, max, 1);
std::thread t2(addToList, max, 10);
t1.join();
t2.join();
std::thread t3(printList);
t3.join();
return 0;
}
t1
|-- loop[0 max]{ / calculate interval / adding number at the end of list} -->[End of t1]
t2
|-- loop[0 max]{ / calculate interval / adding number at the end of list} -->[End of t2]
t3
|-- Rd & Prnt -->[End of t3]
考虑到t1和t2不会同时启动,出于实际目的,我对其进行了表示。