Linux多線程Pthread學習小結

來源:互聯網
上載者:User

簡介

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

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

 

多線程建立

參考代碼:

#include<stdio.h><br />#include<pthread.h><br />#include<string.h><br />#include<sys/types.h><br />#include<unistd.h><br />pthread_t main_tid;<br />void print_ids(const char *str)<br />{<br /> pid_t pid; //進程id<br /> pthread_t tid; //線程id<br /> pid = getpid(); //擷取當前進程id<br /> tid = pthread_self(); //擷取當前線程id<br /> printf("%s pid: %u tid: %u (0x%x)/n",<br /> str,<br /> (unsigned int)pid,<br /> (unsigned int)tid,<br /> (unsigned int)tid);<br />}<br />void *func(void *arg)<br />{<br /> print_ids("new thread:");<br /> return ((void *)0);<br />}<br />int main()<br />{<br /> int err;<br /> err = pthread_create(&main_tid, NULL, func, NULL); //建立線程<br /> if(err != 0){<br /> printf("create thread error: %s/n",strerror(err));<br /> return 1;<br /> }<br /> printf("main thread: pid: %u tid: %u (0x%x)/n",<br /> (unsigned int)getpid(),<br /> (unsigned int)pthread_self(),<br /> (unsigned int)pthread_self());<br /> print_ids("main thread:");<br /> sleep(1);<br /> return 0;<br />}<br /> 

運行結果:

[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)

 

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

 

多線程條件變數

參考代碼:

#include <stdio.h><br />#include <pthread.h><br />#include <unistd.h></p><p>pthread_mutex_t counter_lock; //互斥鎖<br />pthread_cond_t counter_nonzero; //條件變數<br />int counter = 0;<br />int estatus = -1;</p><p>void *decrement_counter(void *argv);<br />void *increment_counter(void *argv);</p><p>//******* 主函數 *******//<br />int main(int argc, char **argv)<br />{<br /> printf("counter: %d/n", counter);<br /> pthread_t thd1, thd2;<br /> int ret;</p><p> //初始化<br /> pthread_mutex_init(&counter_lock, NULL);<br /> pthread_cond_init(&counter_nonzero, NULL);</p><p> ret = pthread_create(&thd1, NULL, decrement_counter, NULL); //建立線程1<br /> if(ret){<br /> perror("del:/n");<br /> return 1;<br /> }</p><p> ret = pthread_create(&thd2, NULL, increment_counter, NULL); //建立線程2<br /> if(ret){<br /> perror("inc: /n");<br /> return 1;<br /> }</p><p> int counter = 0;<br /> while(counter != 10){<br /> printf("counter(main): %d/n", counter); //主線程<br /> sleep(1);<br /> counter++;<br /> }</p><p> pthread_exit(0);</p><p> return 0;<br />}</p><p>void *decrement_counter(void *argv)<br />{<br /> printf("counter(decrement): %d/n", counter);<br /> pthread_mutex_lock(&counter_lock);<br /> while(counter == 0)<br /> pthread_cond_wait(&counter_nonzero, &counter_lock); //進入阻塞(wait),等待啟用(signal)</p><p> printf("counter--(before): %d/n", counter);<br /> counter--; //等待signal啟用後再執行<br /> printf("counter--(after): %d/n", counter);<br /> pthread_mutex_unlock(&counter_lock); </p><p> return &estatus;<br />}</p><p>void *increment_counter(void *argv)<br />{<br /> printf("counter(increment): %d/n", counter);<br /> pthread_mutex_lock(&counter_lock);<br /> if(counter == 0)<br /> pthread_cond_signal(&counter_nonzero); //啟用(signal)阻塞(wait)的線程(先執行完signal線程,然後再執行wait線程)</p><p> printf("counter++(before): %d/n", counter);<br /> counter++;<br /> printf("counter++(after): %d/n", counter);<br /> pthread_mutex_unlock(&counter_lock);</p><p> return &estatus;<br />}<br />

運行結果:

[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

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

 

多線程的建立特殊資料鍵

參考代碼:

#include <stdio.h><br />#include <pthread.h><br />#include <unistd.h></p><p>pthread_key_t key; //聲明參數key</p><p>void echomsg(void *arg) //析構處理函數<br />{<br /> printf("destruct executed in thread = %u, arg = %p/n",<br /> (unsigned int)pthread_self(),<br /> arg);<br />}</p><p>void *child_1(void *arg)<br />{<br /> pthread_t tid;</p><p> tid = pthread_self();<br /> printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);</p><p> pthread_setspecific(key, (void *)tid); // 與key值綁定的value(tid)<br /> printf("%s: thread %u returns %p/n", // %p 表示輸出指標格式<br /> (char *)arg,<br /> (unsigned int)tid,<br /> pthread_getspecific(key)); // 擷取key值的value<br /> sleep(1);<br /> return NULL;<br />}</p><p>void *child_2(void *arg)<br />{<br /> pthread_t tid;</p><p> tid = pthread_self();<br /> printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);</p><p> pthread_setspecific(key, (void *)tid);<br /> printf("%s: thread %u returns %p/n",<br /> (char *)arg,<br /> (unsigned int)tid,<br /> pthread_getspecific(key));<br /> sleep(1);<br /> return NULL;<br />}</p><p>//******* 主函數 *******//<br />int main(void)<br />{<br /> pthread_t tid1, tid2;</p><p> printf("hello main/n");</p><p> pthread_key_create(&key, echomsg); //建立key</p><p> pthread_create(&tid1, NULL, child_1, (void *)"child_1"); //建立帶參數的線程,需要強制轉換<br /> pthread_create(&tid2, NULL, child_2, (void *)"child_2");</p><p> sleep(3);<br /> pthread_key_delete(key); //清除key<br /> printf("bye main/n");</p><p> pthread_exit(0);<br /> return 0;<br />}<br />

運行結果:

[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.htmlhttp://xunet.blog.51cto.com/138167/22011(推薦)

 

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

多線程的建立特殊資料鍵

參考代碼:

#include <stdio.h><br />#include <pthread.h><br />#include <unistd.h></p><p>pthread_once_t once = PTHREAD_ONCE_INIT; //聲明變數</p><p>//once_run()函數僅執行一次,且究竟在哪個線程中執行是不定的<br />//儘管pthread_once(&once,once_run)出現在兩個線程中<br />//函數原型:int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))<br />void once_run(void)<br />{<br /> printf("Func: %s in thread: %u/n",<br /> __func__,<br /> (unsigned int)pthread_self());<br />}</p><p>void *child_1(void *arg)<br />{<br /> pthread_t tid;</p><p> tid = pthread_self();<br /> pthread_once(&once, once_run); //調用once_run<br /> printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);</p><p> return NULL;<br />}</p><p>void *child_2(void *arg)<br />{<br /> pthread_t tid;</p><p> tid = pthread_self();<br /> pthread_once(&once, once_run); //調用once_run<br /> printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);</p><p> return NULL;<br />}</p><p>//******* main *******//<br />int main(void)<br />{<br /> pthread_t tid1, tid2;</p><p> printf("hello main/n");<br /> pthread_create(&tid1, NULL, child_1, (void *)"child_1");<br /> pthread_create(&tid2, NULL, child_2, (void *)"child_2");</p><p> pthread_join(tid1, NULL); //main主線程等待線程tid1返回<br /> pthread_join(tid2, NULL); //main主線程等待線程tid2返回<br /> printf("bye main/n");</p><p> return 0;<br />}<br />

運行結果:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.