簡介
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(): 查詢線程自身線程標識號
?
詳細請參見:
linux多線程pthread:??? ?http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5920936.aspx?
Pthread多線程學習小結: http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5921003.aspx
===================================================================
?
多線程創建
參考代碼:
[cpp] view plaincopy print?
#include<stdio.h>??#include<pthread.h>??#include<string.h>??#include<sys/types.h>??#include<unistd.h>??pthread_t?main_tid;??void?print_ids(const?char?*str)??{??????pid_t?pid;????????????pthread_t?tid;????????pid?=?getpid();?????????????tid?=?pthread_self();???????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;??}??
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
pthread_t main_tid;
void print_ids(const char *str)
{pid_t pid; //進程idpthread_t tid; //線程idpid = getpid(); //獲取當前進程idtid = pthread_self(); //獲取當前線程idprintf("%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;
}
?
運行結果:
[work@db-testing-com06-vm3.db01.baidu.com pthread]$ gcc -Wall -o pthread_create pthread_create.c -lpthread ??
[work@db-testing-com06-vm3.db01.baidu.com 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);???????if(ret){??????????perror("del:/n");??????????return?1;??????}????????ret?=?pthread_create(&thd2,?NULL,?increment_counter,?NULL);???????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);?????????????printf("counter--(before):?%d/n",?counter);??????????counter--;???????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);?????????printf("counter++(before):?%d/n",?counter);??????????counter++;???????printf("counter++(after):?%d/n",?counter);??????????pthread_mutex_unlock(&counter_lock);????????return?&estatus;??}??
#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); //創建線程1if(ret){perror("del:/n");return 1;}ret = pthread_create(&thd2, NULL, increment_counter, NULL); //創建線程2if(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;
}
運行結果:
[work@db-testing-com06-vm3.db01.baidu.com pthread]$ gcc -Wall -o pthread_cond2 pthread_cond2.c -lpthread
[work@db-testing-com06-vm3.db01.baidu.com 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
?
詳細解釋,請見:http://blog.csdn.net/Sunboy_2050/archive/2010/11/24/6031723.aspx
===================================================================
?
多線程的創建特殊數據鍵
參考代碼:
[cpp] view plaincopy print?
#include?<stdio.h>??#include?<pthread.h>??#include?<unistd.h>????pthread_key_t?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);????????printf("%s:?thread?%u?returns?%p/n",??????????????????????(char?*)arg,??????????????????(unsigned?int)tid,???????????????????pthread_getspecific(key));????????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);?????????????pthread_create(&tid1,?NULL,?child_1,?(void?*)"child_1");???????pthread_create(&tid2,?NULL,?child_2,?(void?*)"child_2");????????sleep(3);??????pthread_key_delete(key);???????printf("bye?main/n");????????????pthread_exit(0);??????return?0;??}??
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>pthread_key_t key; //聲明參數keyvoid 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值的valuesleep(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); //創建keypthread_create(&tid1, NULL, child_1, (void *)"child_1"); //創建帶參數的線程,需要強制轉換pthread_create(&tid2, NULL, child_2, (void *)"child_2");sleep(3);pthread_key_delete(key); //清除keyprintf("bye main/n");pthread_exit(0);return 0;
}
運行結果:
[work@db-testing-com06-vm3.db01.baidu.com pthread]$ gcc -Wall -o pthread_setspecific pthread_setspecific.c -lpthread
[work@db-testing-com06-vm3.db01.baidu.com pthread]$ ./pthread_setspecific??????????????????????????????????????????
hello main
child_1: thread 1084229984 enter
child_1: thread 1084229984 returns 0x40a00960
child_2: thread 1094719840 enter
child_2: thread 1094719840 returns 0x41401960
destruct executed in thread = 1084229984, arg = 0x40a00960
destruct executed in thread = 1094719840, arg = 0x41401960
bye 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) 參考網址: http://blog.sina.com.cn/s/blog_46d528490100lxm0.html http://xunet.blog.51cto.com/138167/22011(推薦) ?
===================================================================
多線程的創建特殊數據鍵
參考代碼:
[cpp] view plain copy print?
#include?<stdio.h>??#include?<pthread.h>??#include?<unistd.h>????pthread_once_t?once?=?PTHREAD_ONCE_INIT;???????????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);???????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);???????printf("%s:?thread?%d?returns/n",?(char?*)arg,?(unsigned?int)tid);????????return?NULL;??}??????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);????????pthread_join(tid2,?NULL);????????printf("bye?main/n");????????return?0;??}?? #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_runprintf("%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_runprintf("%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;
}
運行結果:
work@db-testing-com06-vm3.db01.baidu.com pthread]$ gcc -Wall -o pthread_once pthread_once.c -lpthread
[work@db-testing-com06-vm3.db01.baidu.com pthread]$ ./pthread_once???????????????????????????????????
hello main
Func: once_run in thread: 1084229984
child_1: thread 1084229984 returns
child_2: thread 1094719840 returns
bye main
總結
以上是生活随笔為你收集整理的Linux多线程Pthread学习小结的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。