c - pthread_join 在两个无限循环线程上?

标签 c pthreads posix

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

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

最佳答案

您可以按以下顺序执行此操作:

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

关于c - pthread_join 在两个无限循环线程上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7950364/

相关文章:

c - 为什么 snprintf 更改输出字符串?

c++ - 什么时候使用互斥体?

使用线程进行客户端服务器编程

c++ - 什么是 C++ 应用程序的最佳多线程应用程序调试器

bash - 在 bash 中重命名文件的陷阱

c - POSIX 函数来搜索可执行文件的路径?

linux - 如何使用 _FILE_OFFSET_BITS 64 编译的应用程序创建一个小文件(大小 <= 2GB)文件?

C - 不使用 iostream 读取文件

c - 我如何绕开?

c - 为什么我会在 C 中收到此错误?