pthread_exit简介

来源:互联网 发布:mac里的照片导出到u盘 编辑:程序博客网 时间:2024/05/25 05:36
本文转载自:http://baike.baidu.com/view/3361775.htm
  线程通过调用 void pthread_exit(void* retval)函数终止执行,就如同进程在结束时调用exit函数一样。这个函数的作用是,终止调用它的线程并返回一个指向某个对象的指针,该返回值可以通过pthread_join函数的第二个参数得到
  当然执行pthread_exit函数时,通过pthread_cleanup_push压栈的函数会首先被执行,然后如果还有pthread_key_create(pthread_key_t *keyptr, void (* destructor)(void *value))中的 pthread_key_t *keyptr 和非null的数据和它相关联,void (* destructor)(void *value)紧接着会被执行。关于pthread_key_create的更多内容请参考《Posix线程私有数据
示例1

  #include <stdio.h>  #include <stdlib.h>  #include <pthread.h>  void *print_message_function( void *ptr )  {   char *message;   message = (char *) ptr;   printf("%s \t", message);   printf("PID: %ld \n", pthread_self()); /* "thread all done"的指针可以通过pthread_join的第二个参数取得*/   pthread_exit ("thread all done");   }  main()  {   pthread_t thread1, thread2;   char *message1 = "Thread 1";   char *message2 = "Thread 2";   int iret1, iret2;   void *pth_join_ret1;   void *pth_join_ret2;   /* Create independant threads each of which will execute function */   /*pthread_create return 0 if create a thread is ok!*/   iret1 = pthread_create( &thread1, NULL, print_message_function, (void*)"thread one_here");   iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);   pthread_join( thread1, &pth_join_ret1);   pthread_join( thread2, &pth_join_ret2);   /*    if(pth_join_ret1==NULL || pth_join_ret2==NULL)    {    printf("in %d lines \n",__LINE__);    } */   printf("Thread 1 returns: %d\n",iret1);   printf("Thread 2 returns: %d\n",iret2); /*打印 线程退出时的返回值*/   printf("pthread_join 1 returns: %s\n",(char *)pth_join_ret1);   printf("pthread_join 2 returns: %s\n",(char *)pth_join_ret2);   exit(0);  }

结束!
原创粉丝点击