日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > linux >内容正文

linux

Linux多线程Pthread学习小结

發(fā)布時(shí)間:2025/3/15 linux 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linux多线程Pthread学习小结 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

簡(jiǎn)介

POSIX thread 簡(jiǎn)稱為pthread,Posix線程是一個(gè)POSIX標(biāo)準(zhǔn)線程.該標(biāo)準(zhǔn)定義內(nèi)部API創(chuàng)建和操縱線程.

?

作用

線程庫(kù)實(shí)行了POSIX線程標(biāo)準(zhǔn)通常稱為pthreads.pthreads是最常用的POSIX系統(tǒng)如Linux和Unix,而微軟Windowsimplementations同時(shí)存在.舉例來(lái)說(shuō),pthreads-w32可支持MIDP的pthread   

Pthreads定義了一套 C程序語(yǔ)言類型、函數(shù)與常量,它以 pthread.h 頭文件和一個(gè)線程庫(kù)實(shí)現(xiàn)。

?

數(shù)據(jù)類型

pthread_t:線程句柄   

pthread_attr_t:線程屬性

線程操縱函數(shù)(簡(jiǎn)介起見(jiàn),省略參數(shù))

pthread_create():創(chuàng)建一個(gè)線程   

pthread_exit():終止當(dāng)前線程   

pthread_cancel():中斷另外一個(gè)線程的運(yùn)行   

pthread_join():阻塞當(dāng)前的線程,直到另外一個(gè)線程運(yùn)行結(jié)束   

pthread_attr_init():初始化線程的屬性   

pthread_attr_setdetachstate():設(shè)置脫離狀態(tài)的屬性(決定這個(gè)線程在終止時(shí)是否可以被結(jié)合)

pthread_attr_getdetachstate():獲取脫離狀態(tài)的屬性   

pthread_attr_destroy():刪除線程的屬性   

pthread_kill():向線程發(fā)送一個(gè)信號(hào)

?

同步函數(shù)

用于 mutex 和條件變量   

pthread_mutex_init() 初始化互斥鎖   

pthread_mutex_destroy() 刪除互斥鎖   

pthread_mutex_lock():占有互斥鎖(阻塞操作)   

pthread_mutex_trylock():試圖占有互斥鎖(不阻塞操作)。當(dāng)互斥鎖空閑時(shí)將占有該鎖;否則立即返回  

pthread_mutex_unlock(): 釋放互斥鎖   

pthread_cond_init():初始化條件變量   

pthread_cond_destroy():銷毀條件變量   

pthread_cond_wait(): 等待條件變量的特殊條件發(fā)生

pthread_cond_signal(): 喚醒第一個(gè)調(diào)用pthread_cond_wait()而進(jìn)入睡眠的線程   ?  

Thread-local storage(或者以Pthreads術(shù)語(yǔ),稱作 線程特有數(shù)據(jù)):   

pthread_key_create(): 分配用于標(biāo)識(shí)進(jìn)程中線程特定數(shù)據(jù)的鍵   

pthread_setspecific(): 為指定線程特定數(shù)據(jù)鍵設(shè)置線程特定綁定   

pthread_getspecific(): 獲取調(diào)用線程的鍵綁定,并將該綁定存儲(chǔ)在 value 指向的位置中   

pthread_key_delete(): 銷毀現(xiàn)有線程特定數(shù)據(jù)鍵

?

與一起工作的工具函數(shù)

pthread_equal(): 對(duì)兩個(gè)線程的線程標(biāo)識(shí)號(hào)進(jìn)行比較   

pthread_detach(): 分離線程   

pthread_self(): 查詢線程自身線程標(biāo)識(shí)號(hào)

?

詳細(xì)請(qǐng)參見(jiàn):

linux多線程pthread:??? ?http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5920936.aspx?

Pthread多線程學(xué)習(xí)小結(jié): http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5921003.aspx

===================================================================

?

多線程創(chuàng)建

參考代碼:

[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;??????//進(jìn)程id??
  • ????pthread_t?tid;??//線程id??
  • ????pid?=?getpid();???????//獲取當(dāng)前進(jìn)程id??
  • ????tid?=?pthread_self();?//獲取當(dāng)前線程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);?//創(chuàng)建線程??
  • ????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; //進(jìn)程idpthread_t tid; //線程idpid = getpid(); //獲取當(dāng)前進(jìn)程idtid = pthread_self(); //獲取當(dāng)前線程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); //創(chuàng)建線程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; } ?

    運(yùn)行結(jié)果:

    [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);??
  • ??
  • //*******?主函數(shù)?*******//??
  • 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);?//創(chuàng)建線程1??
  • ????if(ret){??
  • ????????perror("del:/n");??
  • ????????return?1;??
  • ????}??
  • ??
  • ????ret?=?pthread_create(&thd2,?NULL,?increment_counter,?NULL);?//創(chuàng)建線程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);?//進(jìn)入阻塞(wait),等待激活(signal)??
  • ??????
  • ????printf("counter--(before):?%d/n",?counter);??????
  • ????counter--;?//等待signal激活后再執(zhí)行??
  • ????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)的線程(先執(zhí)行完signal線程,然后再執(zhí)行wait線程)??
  • ??
  • ????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);//******* 主函數(shù) *******// 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); //創(chuàng)建線程1if(ret){perror("del:/n");return 1;}ret = pthread_create(&thd2, NULL, increment_counter, NULL); //創(chuàng)建線程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); //進(jìn)入阻塞(wait),等待激活(signal)printf("counter--(before): %d/n", counter); counter--; //等待signal激活后再執(zhí)行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)的線程(先執(zhí)行完signal線程,然后再執(zhí)行wait線程)printf("counter++(before): %d/n", counter); counter++; printf("counter++(after): %d/n", counter); pthread_mutex_unlock(&counter_lock);return &estatus; }

    運(yùn)行結(jié)果:

    [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

    ?

    詳細(xì)解釋,請(qǐng)見(jiàn):http://blog.csdn.net/Sunboy_2050/archive/2010/11/24/6031723.aspx

    ===================================================================

    ?

    多線程的創(chuàng)建特殊數(shù)據(jù)鍵

    參考代碼:

    [cpp] view plaincopy print?
  • #include?<stdio.h>??
  • #include?<pthread.h>??
  • #include?<unistd.h>??
  • ??
  • pthread_key_t?key;?//聲明參數(shù)key??
  • ??
  • void?echomsg(void?*arg)?//析構(gòu)處理函數(shù)??
  • {??
  • ????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;??
  • }??
  • ??
  • //*******?主函數(shù)?*******//??
  • int?main(void)??
  • {??
  • ????pthread_t?tid1,?tid2;??
  • ??????
  • ????printf("hello?main/n");??
  • ??????
  • ????pthread_key_create(&key,?echomsg);?//創(chuàng)建key??
  • ??????
  • ????pthread_create(&tid1,?NULL,?child_1,?(void?*)"child_1");?//創(chuàng)建帶參數(shù)的線程,需要強(qiáng)制轉(zhuǎn)換??
  • ????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;??
  • }??
  • #include <stdio.h> #include <pthread.h> #include <unistd.h>pthread_key_t key; //聲明參數(shù)keyvoid echomsg(void *arg) //析構(gòu)處理函數(shù) {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; }//******* 主函數(shù) *******// int main(void) {pthread_t tid1, tid2;printf("hello main/n");pthread_key_create(&key, echomsg); //創(chuàng)建keypthread_create(&tid1, NULL, child_1, (void *)"child_1"); //創(chuàng)建帶參數(shù)的線程,需要強(qiáng)制轉(zhuǎn)換pthread_create(&tid2, NULL, child_2, (void *)"child_2");sleep(3);pthread_key_delete(key); //清除keyprintf("bye main/n");pthread_exit(0);return 0; }

    運(yùn)行結(jié)果:

    [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

    ?

    附加參考——函數(shù)原型:

    Posix定義了兩個(gè)API分別用來(lái)創(chuàng)建和注銷TSD:

    int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)) 注銷一個(gè)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)
    參考網(wǎng)址: http://blog.sina.com.cn/s/blog_46d528490100lxm0.html http://xunet.blog.51cto.com/138167/22011(推薦)

    ?

    ===================================================================

    多線程的創(chuàng)建特殊數(shù)據(jù)鍵

    參考代碼:

    [cpp] view plain copy print?
  • #include?<stdio.h>??
  • #include?<pthread.h>??
  • #include?<unistd.h>??
  • ??
  • pthread_once_t?once?=?PTHREAD_ONCE_INIT;?//聲明變量??
  • ??
  • //once_run()函數(shù)僅執(zhí)行一次,且究竟在哪個(gè)線程中執(zhí)行是不定的??
  • //盡管pthread_once(&once,once_run)出現(xiàn)在兩個(gè)線程中??
  • //函數(shù)原型: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);?//調(diào)用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);?//調(diào)用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;??
  • }??
  • #include <stdio.h> #include <pthread.h> #include <unistd.h>pthread_once_t once = PTHREAD_ONCE_INIT; //聲明變量//once_run()函數(shù)僅執(zhí)行一次,且究竟在哪個(gè)線程中執(zhí)行是不定的 //盡管pthread_once(&once,once_run)出現(xiàn)在兩個(gè)線程中 //函數(shù)原型: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); //調(diào)用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); //調(diào)用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; }

    運(yùn)行結(jié)果:

    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

    總結(jié)

    以上是生活随笔為你收集整理的Linux多线程Pthread学习小结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。