C pthread_在两个无限循环线程上联接?
我刚刚读到,当主循环结束时,任何有或没有机会繁殖的线程都会终止。所以我需要在每个线程上进行连接,以等待它返回C pthread_在两个无限循环线程上联接?,c,pthreads,posix,C,Pthreads,Posix,我刚刚读到,当主循环结束时,任何有或没有机会繁殖的线程都会终止。所以我需要在每个线程上进行连接,以等待它返回 我的问题是,我将如何编写一个程序,在其中创建两个线程,它们在一个无限循环中运行?如果我等待加入一个无限线程,第二个线程将永远不会有机会被创建 您可以使用以下顺序执行此操作: pthread_create thread1 pthread_create thread2 pthread_join thread1 pthread_join thread2 换句话说,在尝试加入任何线程之前,先启
我的问题是,我将如何编写一个程序,在其中创建两个线程,它们在一个无限循环中运行?如果我等待加入一个无限线程,第二个线程将永远不会有机会被创建 您可以使用以下顺序执行此操作:
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;
}
pthread_join
的两个主要用途是:(1)在创建的线程完成之前进行阻塞的方便方法;(2) 实际上,您对在pthread\u join
中创建的线程返回的结果感兴趣
如果在main中没有进一步的工作要做,而只是阻塞以防止整个进程终止,那么可以使用pthread\u exit
退出main。Main将退出,但生成的线程将继续
如果您对返回代码不感兴趣,您可以轻松地创建分离的线程和pthread\u exit
main
在创建的线程中使用“无限”循环不是最佳实践。通常,您希望使线程能够自行关闭。在线程内部,这可能是eof条件、闭合套接字或其他情况。通常,您希望线程能够从一个或多个其他外部线程干净地关闭自己。检查无限循环内的开关和类似方法是实现这一点的最简单方法。否则,您必须执行pthread_cancel路径、捕获信号等,这一切都有点复杂。在加入任何一个之前创建两个?是的@zneak是正确的。我后来意识到了这一点。两个答案都是正确的。
thread 0x28cce4
thread 0x28cce8
thread 0x28ccec
main 0x28ccec
main 0x28cce8
main 0x28cce4