創建一個線程
關於線程的頭文件
#include <pthread.h>
pthread_t用來聲明線程ID
typedef unsigned long int pthread_t;
所有包含這個頭文件里邊的函數,在編譯和鏈接的時候都要加上一個參數
-pthread
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
這個函數會在調用進程中起一個新的線程,新的線程通過調用start_routine這個函數開始執行,arg為start_routine函數的參數(如果沒有,則默認為NULL),新啟動的線程會以以下幾種方式結束
- 它調用了pthread_exit(3), 對於同一個進程中的另外一個線程調用了pthread_join(3)指定了一個結束狀態值.
- start_routine執行完畢
- 這個線程被取消執行(pthread_cancel(3))
- main函數執行完畢
attr指向一個pthread_attr_t結構體, 這個結構體包含了需要創建線程的各種屬性, 如果attr是NULL的話,新的進程就會以默認屬性創建.在這個函數返回之前,一個成功調用pthread_create()的線程ID會存儲在thread中,這個ID標識了所創建的線程
pthread_t pthread_self(void);
這個函數返回調用線程的ID.這個值與pthread_create()中創建的線程的ID相同(thread), 這個函數總會執行成功的.
int pthread_join(pthread_t thread, void **retval);
pthread_join這個函數會等待直到thread所指定的線程執行完畢. 如果thread已經執行完畢,這個函數會立即返回.但是,thread所指定的線程必須是joinable,什么是joinable呢?
一個線程是可連接的,當且僅當它描述了一個可執行的線程
一個線程是不可連接的,當他符合以下任意一種情況
- if it was default-constructed.
- if it has been moved from (either constructing another thread object, or assigning to it).
- if either of its members join or detach has been called.
代碼中如果沒有pthread_join, 主線程會很快結束從而使整個進程結束,創建的線程就沒有機會開始執行就結束了. 加入pthread_join后,主線程會一直等待直到等待的線程結束自己才結束, 使創建的線程有機會執行.