【问题标题】:pthread_join on two infinite loop threads?pthread_join 在两个无限循环线程上?
【发布时间】:2011-10-31 05:52:25
【问题描述】:

我刚刚读到here,当主循环结束时,任何有机会或没有机会产生的线程都将终止。所以我需要在每个线程上做一个连接等待它返回。

我的问题是,我将如何编写一个程序来创建 2 个在无限循环中运行的线程?如果我等待加入一个无限线程,第二个线程将永远没有机会被创建!

【问题讨论】:

  • 在加入其中一个之前创建两个?
  • 是的@zneak 是对的。后来我意识到了。两个答案都是正确的。

标签: c pthreads posix


【解决方案1】:

你可以用这个序列来做到这一点:

pthread_create thread1
pthread_create thread2
pthread_join thread1
pthread_join thread2

换句话说,在尝试加入 任何 个线程之前,请先启动 所有 个线程。更详细地说,您可以从以下程序开始:

#include <stdio.h>
#include <pthread.h>

void *myFunc (void *id) {
    printf ("thread %p\n", id);
    return id;
}

int main (void) {
    pthread_t tid[3];
    int tididx;
    void *retval;

    // Try for all threads, accept less.

    for (tididx = 0; tididx < sizeof(tid) / sizeof(*tid); tididx++)
        if (pthread_create (&tid[tididx], NULL, &myFunc, &tid[tididx]) != 0)
            break;

    // Not starting any is pretty serious.

    if (tididx == 0)
        return -1;

    // Join to all threads that were created.

    while (tididx > 0) {
        pthread_join (tid[--tididx], &retval);
        printf ("main %p\n", retval);
    }

    return 0;
}

这将尝试在加入任何线程之前启动三个线程,然后它将以相反的顺序加入它设法开始的所有线程。正如预期的那样,输出是:

thread 0x28cce4
thread 0x28cce8
thread 0x28ccec
main 0x28ccec
main 0x28cce8
main 0x28cce4

【讨论】:

    【解决方案2】:

    pthread_join 的两个主要用途是 (1) 一种方便的阻塞方式,直到创建的线程完成; (2) 你实际上对pthread_join中创建的线程返回的结果感兴趣。

    如果您在 main 中没有进一步的工作要做并且您只是阻塞以防止整个进程终止,那么您可以使用 pthread_exit 退出 main。 Main 将退出,但生成的线程将继续。

    如果您对返回码不感兴趣,您可以像 detached 和 pthread_exit main 一样轻松创建线程。

    在创建的线程中有一个“无限”循环并不是最佳做法。通常,您希望使线程能够自行关闭。在线程内部,这可能是一个 eof 条件、关闭的套接字或其他任何东西。通常,您还希望使线程能够从一个或多个其他外部线程完全关闭。检查无限循环内的开关和类似方法是完成此操作的最简单方法。否则你必须走 pthread_cancel 路线,捕捉信号等等。所有这些都有点复杂。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2019-04-12
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多