【问题标题】:Make pthread wait for another's data让 pthread 等待另一个人的数据
【发布时间】:2015-04-28 15:29:43
【问题描述】:

我正在尝试构建一个程序,其中 pthread 等待来自前一个 pthread 的信号运行,并在完成时发出下一个 pthread 的信号。

例如,假设我有 4 个 pthread。 #1 首先运行。我希望 #2 在开始执行之前等待 #1 完成,并且在完成后,它将发出 #3 信号。 #3 等待 #2,并最终发出 #4 信号。 #4 完成后简单地终止。

我如何做到这一点?

【问题讨论】:

  • 听起来你要么想要一个互斥锁,要么想要一个条件变量。
  • 建议 1 - 不要使用超过一个线程。
  • 建议 2 - 创建线程 2 作为线程一的最后一行,依此类推....
  • 建议 3 - 搜索所有 dup 的这种不合逻辑的功能。
  • @MartinJames 如果你想写一个答案,写一个答案。

标签: c++ c pthreads


【解决方案1】:

对于这个问题,您不需要条件变量或互斥体。 pthread_join() 就足够了。

将前一个线程的线程 id 传递给它的后继线程。允许后继者调用pthread_join(),等待前继者完成。

main() 只需要在最后一个线程上pthread_join()

但是,如 cmets 中所述,在单个线程中更有效地实现该功能。


C 中的解决方案可能类似于:

static void
wait_for_thread(pthread_t *t)
{
    if (t) {
        pthread_join(*t, 0);
        printf("Thread %zu finished...\n", t - threads);
    }
}

static void *
thread_fun(void *arg)
{
    wait_for_thread(arg);
    /* ... */
    return 0;
}

int main ()
{
    int i;
    for (i = 0; i < 4; ++i) {
        pthread_create(&threads[i], 0, thread_fun, i ? &threads[i-1] : 0);
    }
    wait_for_thread(&threads[3]);
    return 0;
}

C++ 中的解决方案可能类似于:

int main ()
{
    std::array<std::thread, 4> threads;
    auto wait_for_thread = [&threads](int p) {
        if (p >= 0) {
            threads[p].join();
            std::cout << "Thread " << p << " finished...\n";
        }
    };
    auto thread_fun = [&wait_for_thread](int p) {
        wait_for_thread(p);
        //...
    };

    for (auto &t : threads) {
        t = std::thread(thread_fun, &t-&threads[0]-1);
    }
    wait_for_thread(3);
}

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2021-07-13
    • 2021-01-02
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    相关资源
    最近更新 更多