用來建立新的執行緒,並以函數指標指定子執行緒所要執行的函數,子執行緒在建立之後,就會以平行的方式執行,在子執行緒的執行期間,主執行緒還是可以正常執行自己的工作,最後主執行緒再以 pthread_join
函數等待子執行緒執行結束。
/* Create a new thread, starting with execution of START-ROUTINE
getting passed ARG. Creation attributed come from ATTR. The new
handle is stored in *NEWTHREAD. */
extern int pthread_create (pthread_t *__restrict __newthread,
const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg) __THROWNL __nonnull ((1, 3));
使用時需要 #include <pthread.h>
如函式執行成功則回傳 0,失敗則回傳 Error code。
第一個參數 *__newthread
為指向執行緒識別符號的指標。
第二個參數 *__attr
用來設定執行緒屬性。
第三個參數 void *(*__start_routine) (void *)
是執行緒執行函式的起始地址。
最前面的 void *
代表回傳的是void pointer,後面的 (void *)
代表接收void pointer當作傳入參數。
第四個參數 *__arg
是傳入執行函式的參數。
範例
pthread_create(&receive_ip4_thread, NULL, do_something_func, this);
/* Make calling thread wait for termination of the thread TH. The
exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
is not NULL.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_join (pthread_t __th, void **__thread_return);
如函式執行成功則回傳 0,失敗則回傳 Error code。
這個函式是一個執行緒阻塞的函式,呼叫它的函式將一直等待到 __th
的執行緒結束為止,當函式返回時,__th
執行緒的資源將被收回。
第一個參數 __th
為被等待的執行緒識別符號
第二個參數 **__thread_return
為一個使用者定義的指標,它用來儲存 __th
執行緒的返回值。
範例
pthread_join(thread1,NULL);