linux:C++多線程編程小結


mark: 在多線程中使用 cout打印輸出時會出現亂序, printf則沒有該現象.

參考:http://www.cnblogs.com/gnuhpc/archive/2012/12/07/2807484.html

  http://www.cnblogs.com/xianghang123/archive/2011/08/11/2134927.html

·線程創建

  函數原型:int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);

  返回值:若是成功建立線程返回0,否則返回錯誤的編號。  

   形式參數:pthread_t *restrict tidp 要創建的線程的線程id指針,即,創建成功后,該指針指向的內存存放創建線程的id;const pthread_attr_t *restrict attr創建線程時的線程屬性;void* (start_rtn)(void)返回值是void類型的指針函數;void *restrict arg start_rtn的形參。

  ·線程掛起:該函數的作用使得當前線程掛起,等待另一個線程返回才繼續執行。也就是說當程序運行到這個地方時,程序會先停止,然后等線程id為thread的這個線程返回,然后程序才會斷續執行。

  函數原型:int pthread_join( pthread_t thread, void **value_ptr);

  參數說明如下:thread等待退出線程的線程號;value_ptr退出線程的返回值。

  ·線程退出

  函數原型:void pthread_exit(void *rval_ptr);

  ·獲取當前線程id

  函數原型:pthread_t pthread_self(void);

  ·互斥鎖

  創建pthread_mutex_init;銷毀pthread_mutex_destroy;加鎖pthread_mutex_lock;解鎖pthread_mutex_unlock。

  ·條件鎖

  創建pthread_cond_init;銷毀pthread_cond_destroy;觸發pthread_cond_signal;廣播pthread_cond_broadcast S;等待pthread_cond_wait

實例代碼;

 1 #include <pthread.h>
 2 #include <iostream>
 3 using namespace std;
 4 void *TestThread(void* arg)
 5 {
 6   int input = *(int*)arg;
 7   cout << "threadId: "<< input <<"running"<<endl;
 8 }
 9 
10 int main()
11 {
12   pthread_t threadId;
13   int input = 12;
14   int ret = pthread_create(&threadId, NULL, TestThread, (void*)&input);
15   if(ret != 0)
16    {
17     cout<< "create thread error"<<endl;
18    }
19 
20   cout<<"main thread running"<<endl;
21   pthread_join(threadId,NULL);
22 
23   return 0;
24 }


互斥鎖與條件變量以及信號量介紹:
互斥鎖:互斥鎖用來對共享資源的互斥訪問,一個時刻只允許一個線程資源的修改.
pthread_mutex_t mutex;   pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
條件變量: 條件變量的作用是當一個線程的繼續運行依賴於一個條件,而這個條件是由另一個線程觸發的,這時候使用互斥鎖是不行的.
pthread_cond_t cond; pthread_cond_wait(&cond,&mutex); pthread_cond_signal(&cond);
pthread_cond_wait,兩個參數第一個是等待的條件量,第二個是要釋放的互斥鎖,pthread_cond_wait時,阻塞當前線程,等待條件變化,同時釋放自己占有的互斥鎖,使得其他線程可以運行從而觸發條件量,在另一個線程中使用pthread_cond_signal 來告訴被阻塞的線程繼續運行.

信號量:當共享資源有限時,如消費緩沖區,多個線程同時去進行消費,當緩沖區資源為0時,不允許新的線程進入,則使用信號量機制進行限制.信號量一般和互斥鎖接合使用,前者用來限制線程進入緩沖區的數目,后者用於互斥的修改緩沖區資源.
sem_t sem_id; sem_wait(&sem_id);取得信號量,sem_id的值--,若為0,則等待 sem_post(&sem_id);釋放信號量,sem_id++


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM