#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])//main
{
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
pthread_mutex_lock(&lock);
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);//creating thread
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
当一个线程被释放时如何杀死剩余的所有线程
最佳答案
杀死另一个线程是糟糕的设计。标准设计是使用变量来指示线程它应该完成。每个线程应在代码中的适当位置检查变量并相应退出。
原因是只有线程知道什么时候退出,然后它才能自行清理。
关于c - 当我们从任何一个线程中出来时,如何杀死剩余的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075001/