void pthread_exit(void *retval); 參數:retval表示線程退出狀態,通常傳NULL。
作用:將單個線程退出。
注意幾點:
- return的作用是返回到函數的調用點,如果是main函數中的return,則代表該進程結束,并釋放進程地址空間,所有線程都終止。對于其它函數的return,則直接返回到函數的調用點。exit和_exit函數會直接終止整個進程,導致所有線程結束。pthread_exit函數則會導致調用該函數的線程結束。所以,多線程環境中,應盡量少用,或者不使用exit函數,取而代之使用pthread_exit函數,將單個線程退出。任何線程里exit導致進程退出,其他線程也結束,主控線程退出時不能return或exit。
- 另注意,pthread_exit或者return返回的指針(線程執行的函數用return或者pthread_exit結束線程時)所指向的內存單元必須是全局的或者是用malloc分配的,不能在線程函數的棧上分配,因為當其它線程得到這個返回指針時線程函數已經退出了,此時退出的這個線程函數所占據的棧空間可能又會被重新分配出去,因此其他線程再次使用這個返回的地址沒有意義。
//代碼示例
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>void *tfn(void *arg)
{int s = (int)arg;printf("The %dth thread: the process id is %d and thread id is %lu.\n",s+1,getpid( ),pthread_self( ));return NULL;
}int main(int argc,char *argv[ ])
{pthread_t tid;int ret, i, n=5;if(argc == 2)n = atoi(argv[1]);for( i=0;i<n;i++ ){ret = pthread_create(&tid, NULL, tfn,(void *)i);if( ret != 0 ){fprintf(stderr,"pthread_create error: %s\n",strerror(ret));exit(1);}}printf("In main: the process id is %u and thread id is %lu.\n",getpid( ),pthread_self( ));pthread_exit( NULL );
}
[root@localhost 01_pthread_test]# ./pthrd_crt 10
The 1th thread: the process id is 9035 and thread id is 4149640000.
The 4th thread: the process id is 9035 and thread id is 4124461888.
The 7th thread: the process id is 9035 and thread id is 4099283776.
The 9th thread: the process id is 9035 and thread id is 4082498368.
In main: the process id is 9035 and thread id is 4151699712.
The 6th thread: the process id is 9035 and thread id is 4107676480.
The 8th thread: the process id is 9035 and thread id is 4090891072.
The 5th thread: the process id is 9035 and thread id is 4116069184.
The 10th thread: the process id is 9035 and thread id is 4074105664.
The 2th thread: the process id is 9035 and thread id is 4141247296.
The 3th thread: the process id is 9035 and thread id is 4132854592.
分析:通過使用pthread_exit函數可以不再用sleep函數,此時線程輸出的順序也是無序的。