使一个线程等待另一个线程完成执行



这里是线程新手,在下面的代码中,我希望线程A先完成,然后是线程B。现在,两个主线程都在等待两个线程完成执行。如何让线程B等待线程A执行完毕。我并没有试图实现任何目标,这只是我在书中看到的一个简单的编码练习。

#include <iostream>
#include <thread>
using namespace std;
void run1()
{
cout << "Facebook " << endl;
cout << "Facebook: " << this_thread::get_id() << endl;
}
void run2()
{
cout << "Twitter " << endl;
cout << "Twitter: " << this_thread::get_id() << endl;
}
int main()
{
thread A(run1);
thread B(run2);
A.join();
B.join();
return 0;
}

输出必须为:

Facebook
Facebook:some_thread_id
Twitter
Twitter:some_tthread_id

#include <iostream>
#include <thread>
using namespace std;
void run1()
{
cout << "Facebook " << endl;
cout << "Facebook: " << this_thread::get_id() << endl;
}
void run2(thread *toBeWaited)
{
cout << "Twitter " << endl;
cout << "Twitter: " << this_thread::get_id() << endl;
toBeWaited->join();
}
int main()
{
thread A(run1);
thread B(run2, &A);
B.join();
return 0;
}

在现实世界中,您必须确保a线程的生存期。你也可以在B中启动线程A,或者等待A完成后再启动A。这取决于你的实际情况,哪一个是最好的。

最新更新