1、原型:int pthread_create((pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
用法:#include <pthread.h>
功能:創建線程(實際上就是確定調用該線程函數的入口點),在線程創建以後,就開始運行相關的線程函數。
說明:thread:線程標識符;
attr:線程屬性設置(joinable、detached);
start_routine:線程函數的起始地址;
arg:傳遞給start_routine的參數;
pthread_create建立了線程,需對函數返回值進行判斷:0表示成功,-1表示失敗。
2、pthread_create - create a new thread
A thread may either be joinable or detached. If a thread is
joinable, then another thread can call pthread_join(3) to wait for
the thread to terminate and fetch its exit status. Only when a
terminated joinable thread has been joined are the last of its
resources released back to the system. When a detached thread
terminates, its resources are automatically released back to the
system: it is not possible to join with the thread in order to obtain
its exit status. Making a thread detached is useful for some types
of daemon threads whose exit status the application does not need to
care about. By default, a new thread is created in a joinable state,
unless attr was set to create the thread in a detached state (using
pthread_attr_setdetachstate(3)).
中文意思即:一個線程可以是joinable或者detached狀態的,默認爲joinable。線程是可結合的(joinable),或者是分離的(detached)。一個可結合的線程能夠被其他線程收回其資源和殺死;在被其他線程回收之前,它的存儲器資源(如棧)是不釋放的。相反,一個分離的線程是不能被其他線程回收或殺死的,它的存儲器資源在它終止時由系統自動釋放。
3、The pthread_attr_setdetachstate() function sets the detach state
attribute of the thread attributes object referred to by attr to the
value specified in detachstate. The detach state attribute
determines whether a thread created using the thread attributes
object attr will be created in a joinable or a detached state.
The following values may be specified in detachstate:
PTHREAD_CREATE_DETACHED 1
Threads that are created using attr will be created in a
detached state.
PTHREAD_CREATE_JOINABLE 0
Threads that are created using attr will be created in a
joinable state.
The default setting of the detach state attribute in a newly
initialized thread attributes object is PTHREAD_CREATE_JOINABLE.
The pthread_attr_getdetachstate() returns the detach state attribute
of the thread attributes object attr in the buffer pointed to by
detachstate.
在線程設置爲joinable後,可以調用pthread_detach()使之成爲detached。但是相反的操作則不可以。還有,如果線程已經調用pthread_join()後,則再調用pthread_detach()則不會有任何效果。
線程如果設置爲detached屬性,則在後面調用pthread_join()失效。pthread_join()必須將線程屬性設置爲joinable纔會生效。
線程的分離狀態決定一個線程以什麼樣的方式來終止自己。在默認情況下線程是非分離狀態的,這種情況下,原有的線程等待創建的線程結束。只有當pthread_join()函數返回時,創建的線程纔算終止,才能釋放自己佔用的系統資源。而分離線程不是這樣子的,它沒有被其他的線程所等待,自己運行結束了,線程也就終止了,馬上釋放系統資源。程序員應該根據自己的需要,選擇適當的分離狀態。所以如果我們在創建線程時就知道不需要了解線程的終止狀態,則可以pthread_attr_t結構中的detachstate線程屬性,讓線程以分離狀態啓動。
4、非靜態的成員函數是不能作爲線程函數啓動的
在C++的類中,普通成員函數不能作爲pthread_create的線程函數,如果要作爲pthread_create中的線程函數,必須是static !
在C語言中,我們使用pthread_create創建線程,線程函數是一個全局函數,所以在C++中,創建線程時,也應該使用一個全局函數。static定義的類的成員函數就是一個全局函數。