我可以看到
main()
被APIpthread_exit()
阻塞,我也见过一些例子,其中主函数被APIpthread_join()
阻塞。我不明白什么时候使用什么?我参考了以下网站-https://computing.llnl.gov/tutorials/pthreads/。我无法理解何时使用
pthread_join()
和何时使用pthread_exit()
的概念。有人能解释一下吗?同时,欢迎提供一个好的pthread教程链接。
#include <pthread.h>
#include <stdio.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[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
意识到了另一件事,即
pthread_cancel(thread);
pthread_join(thread, NULL);
有时候,在线程执行时,你可能想要取消它。 你可以使用 pthread_cancel(thread); 来实现。 但是,请记住你需要启用 pthread 取消支持。 同时,还需要进行取消时的清理工作。
thread_cleanup_push(my_thread_cleanup_handler, resources);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
static void my_thread_cleanup_handler(void *arg)
{
// free
// close, fclose
}