【问题标题】:Making a thread wait for another thread to finish the execution让一个线程等待另一个线程完成执行
【发布时间】:2021-06-21 04:14:35
【问题描述】:

这里是线程新手,在下面的代码中,我希望线程 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
推特:some_thread_id

【问题讨论】:

  • 将一个线程的引用传递给需要等待的线程?
  • 在线程 B 中等待 A 完成。
  • 你能分享一个相同的代码sn-p吗?
  • 您已经有适当的join 呼叫。只需将其移入run2,然后弄清楚如何传递对线程的引用。至少尝试
  • 你也可以在A.join()之后才启动线程B。

标签: c++ multithreading parallel-processing


【解决方案1】:
#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 完成。这取决于您的实际情况,哪个是最好的。

【讨论】:

  • 非常感谢您的回答@Devolus
猜你喜欢
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
相关资源
最近更新 更多