Linux多執行緒Pthread學習小結
簡介
POSIX thread 簡稱為pthread,Posix執行緒是一個POSIX標準執行緒.該標準定義內部API建立和操縱執行緒.
作用
執行緒庫實行了POSIX執行緒標準通常稱為pthreads.pthreads是最常用的POSIX系統如Linux和Unix,而微軟Windowsimplementations同時存在.舉例來說,pthreads-w32可支援MIDP的pthread
Pthreads定義了一套 C程式語言型別、函式與常量,它以 pthread.h 標頭檔案和一個執行緒庫實現。
資料型別
pthread_t:執行緒控制代碼
pthread_attr_t:執行緒屬性
執行緒操縱函式(簡介起見,省略引數)
pthread_create():建立一個執行緒
pthread_exit():終止當前執行緒
pthread_cancel():中斷另外一個執行緒的執行
pthread_join():阻塞當前的執行緒,直到另外一個執行緒執行結束
pthread_attr_init():初始化執行緒的屬性
pthread_attr_setdetachstate():設定脫離狀態的屬性(決定這個執行緒在終止時是否可以被結合)
pthread_attr_getdetachstate():獲取脫離狀態的屬性
pthread_attr_destroy():刪除執行緒的屬性
pthread_kill():向執行緒傳送一個訊號
同步函式
用於 mutex 和條件變數
pthread_mutex_init() 初始化互斥鎖
pthread_mutex_destroy() 刪除互斥鎖
pthread_mutex_lock():佔有互斥鎖(阻塞操作)
pthread_mutex_trylock():試圖佔有互斥鎖(不阻塞操作)。當互斥鎖空閒時將佔有該鎖;否則立即返回
pthread_mutex_unlock(): 釋放互斥鎖
pthread_cond_init():初始化條件變數
pthread_cond_destroy():銷燬條件變數
pthread_cond_wait(): 等待條件變數的特殊條件發生
pthread_cond_signal(): 喚醒第一個呼叫pthread_cond_wait()而進入睡眠的執行緒
Thread-local storage(或者以Pthreads術語,稱作 執行緒特有資料):
pthread_key_create(): 分配用於標識程序中執行緒特定資料的鍵
pthread_setspecific(): 為指定執行緒特定資料鍵設定執行緒特定繫結
pthread_getspecific(): 獲取呼叫執行緒的鍵繫結,並將該繫結儲存在 value 指向的位置中
pthread_key_delete(): 銷燬現有執行緒特定資料鍵
與一起工作的工具函式
pthread_equal(): 對兩個執行緒的執行緒標識號進行比較
pthread_detach(): 分離執行緒
pthread_self(): 查詢執行緒自身執行緒標識號
詳細請參見:
===================================================================
多執行緒建立
參考程式碼:
[cpp] view plain copy print?- #include<stdio.h>
- #include<pthread.h>
- #include<string.h>
- #include<sys/types.h>
- #include<unistd.h>
- pthread_t main_tid;
- void print_ids(constchar *str)
- {
- pid_t pid; //程序id
- pthread_t tid; //執行緒id
- pid = getpid(); //獲取當前程序id
- tid = pthread_self(); //獲取當前執行緒id
- printf("%s pid: %u tid: %u (0x%x)/n",
- str,
- (unsigned int)pid,
- (unsigned int)tid,
- (unsigned int)tid);
- }
- void *func(void *arg)
- {
- print_ids("new thread:");
- return ((void *)0);
- }
- int main()
- {
- int err;
- err = pthread_create(&main_tid, NULL, func, NULL); //建立執行緒
- if(err != 0){
- printf("create thread error: %s/n",strerror(err));
- return 1;
- }
- printf("main thread: pid: %u tid: %u (0x%x)/n",
- (unsigned int)getpid(),
- (unsigned int)pthread_self(),
- (unsigned int)pthread_self());
- print_ids("main thread:");
- sleep(1);
- return 0;
- }
執行結果:
[[email protected] pthread]$ gcc -Wall -o pthread_create pthread_create.c -lpthread
[[email protected] pthread]$ ./pthread_create
main thread: pid: 12531 tid: 2505487232 (0x9556b380)
main thread: pid: 12531 tid: 2505487232 (0x9556b380)
new thread: pid: 12531 tid: 1084229984 (0x40a00960)
===================================================================
多執行緒條件變數
參考程式碼:
[cpp] view plain copy print?- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- pthread_mutex_t counter_lock; //互斥鎖
- pthread_cond_t counter_nonzero; //條件變數
- int counter = 0;
- int estatus = -1;
- void *decrement_counter(void *argv);
- void *increment_counter(void *argv);
- //******* 主函式 *******//
- int main(int argc, char **argv)
- {
- printf("counter: %d/n", counter);
- pthread_t thd1, thd2;
- int ret;
- //初始化
- pthread_mutex_init(&counter_lock, NULL);
- pthread_cond_init(&counter_nonzero, NULL);
- ret = pthread_create(&thd1, NULL, decrement_counter, NULL); //建立執行緒1
- if(ret){
- perror("del:/n");
- return 1;
- }
- ret = pthread_create(&thd2, NULL, increment_counter, NULL); //建立執行緒2
- if(ret){
- perror("inc: /n");
- return 1;
- }
- int counter = 0;
- while(counter != 10){
- printf("counter(main): %d/n", counter); //主執行緒
- sleep(1);
- counter++;
- }
- pthread_exit(0);
- return 0;
- }
- void *decrement_counter(void *argv)
- {
- printf("counter(decrement): %d/n", counter);
- pthread_mutex_lock(&counter_lock);
- while(counter == 0)
- pthread_cond_wait(&counter_nonzero, &counter_lock); //進入阻塞(wait),等待啟用(signal)
- printf("counter--(before): %d/n", counter);
- counter--; //等待signal啟用後再執行
- printf("counter--(after): %d/n", counter);
- pthread_mutex_unlock(&counter_lock);
- return &estatus;
- }
- void *increment_counter(void *argv)
- {
- printf("counter(increment): %d/n", counter);
- pthread_mutex_lock(&counter_lock);
- if(counter == 0)
- pthread_cond_signal(&counter_nonzero); //啟用(signal)阻塞(wait)的執行緒(先執行完signal執行緒,然後再執行wait執行緒)
- printf("counter++(before): %d/n", counter);
- counter++;
- printf("counter++(after): %d/n", counter);
- pthread_mutex_unlock(&counter_lock);
- return &estatus;
- }
執行結果:
[[email protected] pthread]$ gcc -Wall -o pthread_cond2 pthread_cond2.c -lpthread
[[email protected] pthread]$ ./pthread_cond2
counter: 0
counter(main): 0
counter(decrement): 0
counter(increment): 0
counter++(before): 0
counter++(after): 1
counter--(before): 1
counter--(after): 0
counter(main): 1
counter(main): 2
counter(main): 3
counter(main): 4
counter(main): 5
counter(main): 6
counter(main): 7
counter(main): 8
counter(main): 9
===================================================================
多執行緒的建立特殊資料鍵
參考程式碼:
[cpp] view plain copy print?- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- pthread_key_t key; //宣告引數key
- void echomsg(void *arg) //析構處理函式
- {
- printf("destruct executed in thread = %u, arg = %p/n",
- (unsigned int)pthread_self(),
- arg);
- }
- void *child_1(void *arg)
- {
- pthread_t tid;
- tid = pthread_self();
- printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);
- pthread_setspecific(key, (void *)tid); // 與key值繫結的value(tid)
- printf("%s: thread %u returns %p/n", // %p 表示輸出指標格式
- (char *)arg,
- (unsigned int)tid,
- pthread_getspecific(key)); // 獲取key值的value
- sleep(1);
- return NULL;
- }
- void *child_2(void *arg)
- {
- pthread_t tid;
- tid = pthread_self();
- printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);
- pthread_setspecific(key, (void *)tid);
- printf("%s: thread %u returns %p/n",
- (char *)arg,
- (unsigned int)tid,
- pthread_getspecific(key));
- sleep(1);
- return NULL;
- }
- //******* 主函式 *******//
- int main(void)
- {
- pthread_t tid1, tid2;
- printf("hello main/n");
- pthread_key_create(&key, echomsg); //建立key
- pthread_create(&tid1, NULL, child_1, (void *)"child_1"); //建立帶引數的執行緒,需要強制轉換
- pthread_create(&tid2, NULL, child_2, (void *)"child_2");
- sleep(3);
- pthread_key_delete(key); //清除key
- printf("bye main/n");
- pthread_exit(0);
- return 0;
- }
執行結果:
[[email protected] pthread]$ gcc -Wall -o pthread_setspecific pthread_setspecific.c -lpthread[[email protected] pthread]$ ./pthread_setspecific hello mainchild_1: thread 1084229984 enterchild_1: thread 1084229984 returns 0x40a00960child_2: thread 1094719840 enterchild_2: thread 1094719840 returns 0x41401960destruct executed in thread = 1084229984, arg = 0x40a00960destruct executed in thread = 1094719840, arg = 0x41401960bye main
附加參考——函式原型:
Posix定義了兩個API分別用來建立和登出TSD:
int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *))登出一個TSD採用如下API:int pthread_key_delete(pthread_key_t key)int pthread_setspecific(pthread_key_t key, const void *pointer)void * pthread_getspecific(pthread_key_t key)參考網址:===================================================================
多執行緒的建立特殊資料鍵
參考程式碼:
[cpp] view plain copy print?- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- pthread_once_t once = PTHREAD_ONCE_INIT; //宣告變數
- //once_run()函式僅執行一次,且究竟在哪個執行緒中執行是不定的
- //儘管pthread_once(&once,once_run)出現在兩個執行緒中
- //函式原型:int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
- void once_run(void)
- {
- printf("Func: %s in thread: %u/n",
- __func__,
- (unsigned int)pthread_self());
- }
- void *child_1(void *arg)
- {
- pthread_t tid;
- tid = pthread_self();
- pthread_once(&once, once_run); //呼叫once_run
- printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);
- return NULL;
- }
- void *child_2(void *arg)
- {
- pthread_t tid;
- tid = pthread_self();
- pthread_once(&once, once_run); //呼叫once_run
- printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);
- return NULL;
- }
- //******* main *******//
- int main(void)
- {
- pthread_t tid1, tid2;
- printf("hello main/n");
- pthread_create(&tid1, NULL, child_1, (void *)"child_1");
- pthread_create(&tid2, NULL, child_2, (void *)"child_2");
- pthread_join(tid1, NULL); //main主執行緒等待執行緒tid1返回
- pthread_join(tid2, NULL); //main主執行緒等待執行緒tid2返回
- printf("bye main/n");
- return 0;
- }
執行結果:
[email protected] pthread]$ gcc -Wall -o pthread_once pthread_once.c -lpthread[[email protected] pthread]$ ./pthread_once hello mainFunc: once_run in thread: 1084229984child_1: thread 1084229984 returnschild_2: thread 1094719840 returnsbye main