如果進程中任一線程調用exit, _Exit, _exit, 整個進程終止. 這不是線程終止, 而是進程, 這將終止該進程中的所有線程.
1. 線程終止的方式:
單個線程可以通過3種方式退出:
- 從啟動常式中返回, 傳回值是線程的退出碼.
- 被同一進程中的其他線程取消.
- 調用pthread_exit.
2. pthread_exit函數:
- 原型: void pthread_exit(void *rval_ptr);
- 標頭檔: <pthread.h>
- 參數: rval_ptr是一個無類型指標, 指向線程的傳回值儲存變數.
3. pthread_join函數:
- 原型: int pthread_join(pthread_t thread, void **rval_ptr);
- 標頭檔: <pthread.h>
- 傳回值: 成功則返回0, 否則返回錯誤編號.
- 參數:
- thread: 線程ID.
- rval_ptr: 指向傳回值的指標(傳回值也是個指標).
- 說明:
- 調用線程將一直阻塞, 直到指定的線程調用pthread_exit, 從啟動常式返回或被取消.
- 如果線程從它的啟動常式返回, rval_ptr包含返回碼.
- 如果線程被取消, 由rval_ptr指定的記憶體單元置為: PTHREAD_CANCELED.
- 如果對傳回值不關心, 可把rval_ptr設為NULL.
4. 執行個體:
main.c 代碼:
#include <pthread.h>
#include <stdio.h>
/**//* print process and thread IDs */
void printids(const char *s)
...{
pid_t pid, ppid;
pthread_t tid;
pid = getpid();
ppid = getppid();
tid = pthread_self();
printf("%16s pid %5u ppid %5u tid %16u (0x%x) ",
s, (unsigned int)pid, (unsigned int)ppid,
(unsigned int)tid, (unsigned int)tid);
}
/**//* thread process */
void *thread_func(void *arg);
...{
printids("new thread: ");
return (void *)108;
}
/**//* main func */
int main()
...{
int err;
void *tret; /**//* thread return value */
pthread_t ntid;
err = pthread_create(&ntid, NULL, thread_func, NULL);
if (err != 0)
perror("can't create thread");
err = pthread_join(ntid, &tret);
if (err != 0)
perror("can't join thread");
printids("main thread: ");
printf("thread exit code: %d ", (int)tret);
sleep(1);
return 0;
}
這段代碼是通過前一個執行個體改編的, 執行流程如下:
- 首先建立一個新線程, 該線程在列印完IDs後, 返回108.
- 然後用pthread_join擷取該線程傳回值, 存於tret中.
- 主線程列印IDs.
- 主線程列印tret, 即新線程的傳回值.
5. pthread_cancel函數:
- 原型: int pthread_cancel(pthread_t tid);
- 標頭檔: <pthread.h>
- 傳回值: 成功則返回0, 否則返回錯誤編號.
- 說明:
- 等同於調用了參數為PTHREAD_CANCELED的pthread_exit.
- cancel並不等待線程終止, 它僅僅是提出請求.
- 線程可以選擇忽略取消方式或是控製取消方式.