main() 的執行緒稱為主執行緒(main thread)。pthread_create() 建立的執行緒稱為子執行緒(child thread)。pthread_self()/pthread_equal()pthread_attr_init() 等pthread_create()pthread_detach()/pthread_setcancelstate()/pthread_setcanceltype()pthread_kill()pthread_exit()pthread_cancel()pthread_join()gcc -pthread#include <pthread.h>
// 在呼叫進程中建立新執行緒,透過啟動 start_routine() 開始執行,arg 是其唯一參數
// 成功返回 0,失敗返回 error number
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
thread:存放新執行緒 ID。
attr:執行緒屬性,給 NULL 表示預設。
start_routine:新執行緒的處理函數,執行完畢後執行緒終止。
arg:傳給 start_routine 的實參。
// 等待 thread 指定的執行緒終止;若目標未終止則當前執行緒進入阻塞
// 成功返回 0,失敗返回 error number
int pthread_join(pthread_t thread, void **retval);
thread:執行緒編號。
retval:二級指標,用於帶回目標執行緒的退出狀態;若目標被 cancel,則帶回 PTHREAD_CANCELED。
使用 pthread_create() 建立執行緒並以 pthread_join() 取得退出狀態:
// 使用 pthread_join 獲取目標執行緒的退出狀態
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void* task(void* pv){
char* pc = "hello";
return (void*)pc;
}
main(){
pthread_t thread;
int error = pthread_create(&thread, NULL, task, NULL);
if(0 != error) printf("%s", strerror(error)), exit(-1);
char* ps = NULL;
error = pthread_join(thread, (void**)&ps);
if(0 != error) printf("pthread_join %s\n", strerror(error)), exit(-1);
printf("child thread returned:%s\n", ps);
return 0;
}
使用 pthread_exit() 只結束當前執行緒而不結束進程,並可帶出回傳值:
void* task(void* pv){
static int i = 0;
for(i = 1; i <= 20; i++){
if(10 == i) pthread_exit((void*)&i); // 只結束當前執行緒
else printf("i=%d\n", i);
}
return NULL;
}
使用 pthread_cancel() 取消指定執行緒,取消是否生效取決於執行緒的 state 與 type 屬性;若目標執行緒呼叫 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) 禁止取消,則取消請求不會生效。