二 Linux--多線程( 五 )


#include<stdio.h>#include<pthread.h>#include<unistd.h>//創建條件變量pthread_cond_t cond;//創建互斥鎖pthread_mutex_t mutex;//線程處理函數1void *threadfun1(void *arg){    char* name = (char*)arg;    while(1)    {      pthread_mutex_lock(&mutex);      pthread_cond_wait(&cond,&mutex);      printf("%s is waked up...\n",name);      sleep(1);      pthread_mutex_unlock(&mutex);    }  }//線程處理函數2void *threadfun2(void *arg){    char *name = (char *)arg;    while(1)    {       sleep(1);      //喚醒一個等待隊列中的線程      pthread_cond_signal(&cond);      printf("%s is wakeding up a thread...\n",name);    }}int main(){    pthread_t pthread1,pthread2,pthread3,pthread4,pthread5;    //初始化條件變量    pthread_cond_init(&cond,NULL);    //初始化互斥鎖    pthread_mutex_init(&mutex,NULL);    //創建五個線程    pthread_create(&pthread1,NULL,threadfun1,(void *)"pthread 1");    pthread_create(&pthread2,NULL,threadfun1,(void *)"pthread 2");    pthread_create(&pthread3,NULL,threadfun1,(void *)"pthread 3");    pthread_create(&pthread4,NULL,threadfun1,(void *)"pthread 4");    pthread_create(&pthread5,NULL,threadfun2,(void *)"pthread 5");//等待線程結束    pthread_join(pthread1,NULL);    pthread_join(pthread2,NULL);    pthread_join(pthread3,NULL);    pthread_join(pthread4,NULL);    pthread_join(pthread5,NULL);    pthread_mutex_destroy(&mutex);    pthread_cond_destroy(&cond);    return 0;}運行結果如下:

二 Linux--多線程

文章插圖
值得注意的是pthread_cond_wait在阻塞的時候,會釋放已經掌握的互斥鎖,等到被喚醒的時候,重新上鎖 。
舉個例子:
二 Linux--多線程

文章插圖
其實pthread_cond_wait內部隱藏一次解鎖的過程,如果是fun1先運行,num被上鎖,會阻塞在第24條語句,但是pthread_cond_wait會先解鎖,釋放掉num資源,但依然阻塞在24行 , 此時fun2加鎖,改變條件,函數pthread_cond_signal會喚醒pthread_cond_wait函數,此時num會再次被上鎖,然后解鎖,所以pthread_cond_wait其實在內部做了一次解鎖的操作 。
條件變量其實很簡單,遇到pthread_cond_wait線程就會阻塞在阻塞隊列 , 當pthread_cond_signal調用的時候,就會喚醒在阻塞隊列中的線程,繼續執行下面的代碼 。
【二 Linux--多線程】

推薦閱讀