我刚刚读了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/