我不熟悉pthreads,我正在努力理解它.我看到了如下一些例子.
我可以看到main()
被API pthread_exit()
阻塞,我也看到过主函数被API pthread_join()
阻塞的例子.我不明白什么时候用什么?
我指的是下面的站点-https://computing.llnl.gov/tutorials/pthreads/.我不能理解什么时候用pthread_join()
,什么时候用pthread_exit()
的概念.
谁能解释一下吗?此外,对于pthreads的良好教程链接也将不胜感激.
#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);
有时,您希望在线程执行时取消它.
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
}