Linux系統程式設計(29)——執行緒間同步(續篇)

尹成發表於2014-09-04


執行緒間的同步還有這樣一種情況:執行緒A需要等某個條件成立才能繼續往下執行,現在這個條件不成立,執行緒A就阻塞等待,而執行緒B在執行過程中使這個條件成立了,就喚醒執行緒A繼續執行。在pthread庫中通過條件變數(Condition Variable)來阻塞等待一個條件,或者喚醒等待這個條件的執行緒。Condition Variable用pthread_cond_t型別的變數表示,可以這樣初始化和銷燬:

 

#include <pthread.h>

 

int pthread_cond_destroy(pthread_cond_t*cond);

int pthread_cond_init(pthread_cond_t*restrict cond,

      const pthread_condattr_t *restrict attr);

pthread_cond_t cond =PTHREAD_COND_INITIALIZER;

 

返回值:成功返回0,失敗返回錯誤號。

 

和Mutex的初始化和銷燬類似,pthread_cond_init函式初始化一個Condition Variable,attr引數為NULL則表示預設屬性,pthread_cond_destroy函式銷燬一個Condition Variable。如果Condition Variable是靜態分配的,也可以用巨集定義PTHEAD_COND_INITIALIZER初始化,相當於用pthread_cond_init函式初始化並且attr引數為NULL。ConditionVariable的操作可以用下列函式:

 

#include <pthread.h>

 

int pthread_cond_timedwait(pthread_cond_t*restrict cond,

      pthread_mutex_t *restrict mutex,

      const struct timespec *restrict abstime);

int pthread_cond_wait(pthread_cond_t*restrict cond,

      pthread_mutex_t *restrict mutex);

int pthread_cond_broadcast(pthread_cond_t*cond);

int pthread_cond_signal(pthread_cond_t*cond);

返回值:成功返回0,失敗返回錯誤號。

 

可見,一個Condition Variable總是和一個Mutex搭配使用的。一個執行緒可以呼叫pthread_cond_wait在一個Condition Variable上阻塞等待,這個函式做以下三步操作:

 

1、釋放Mutex

2、阻塞等待

3、當被喚醒時,重新獲得Mutex並返回

 

pthread_cond_timedwait函式還有一個額外的引數可以設定等待超時,如果到達了abstime所指定的時刻仍然沒有別的執行緒來喚醒當前執行緒,就返回ETIMEDOUT。一個執行緒可以呼叫pthread_cond_signal喚醒在某個Condition Variable上等待的另一個執行緒,也可以呼叫pthread_cond_broadcast喚醒在這個Condition Variable上等待的所有執行緒。

 

下面的程式演示了一個生產者-消費者的例子,生產者生產一個結構體串在連結串列的表頭上,消費者從表頭取走結構體。

 

#include <stdlib.h>

#include <pthread.h>

#include <stdio.h>

 

struct msg {

         structmsg *next;

         intnum;

};

 

struct msg *head;

pthread_cond_t has_product =PTHREAD_COND_INITIALIZER;

pthread_mutex_t lock =PTHREAD_MUTEX_INITIALIZER;

 

void *consumer(void *p)

{

         structmsg *mp;

 

         for(;;) {

                   pthread_mutex_lock(&lock);

                   while(head == NULL)

                            pthread_cond_wait(&has_product,&lock);

                   mp= head;

                   head= mp->next;

                   pthread_mutex_unlock(&lock);

                   printf("Consume%d\n", mp->num);

                   free(mp);

                   sleep(rand()% 5);

         }

}

 

void *producer(void *p)

{

         structmsg *mp;

         for(;;) {

                   mp= malloc(sizeof(struct msg));

                   mp->num= rand() % 1000 + 1;

                   printf("Produce%d\n", mp->num);

                   pthread_mutex_lock(&lock);

                   mp->next= head;

                   head= mp;

                   pthread_mutex_unlock(&lock);

                   pthread_cond_signal(&has_product);

                   sleep(rand()% 5);

         }

}

 

int main(int argc, char *argv[])

{

         pthread_tpid, cid; 

 

         srand(time(NULL));

         pthread_create(&pid,NULL, producer, NULL);

         pthread_create(&cid,NULL, consumer, NULL);

         pthread_join(pid,NULL);

         pthread_join(cid,NULL);

         return0;

}執行結果如下:

 

Produce 744

Consume 744

Produce 567

Produce 881

Consume 881

Produce 911

Consume 911

Consume 567

Produce 698

Consume 698

 

在這個例子中,生產者和消費者訪問連結串列的順序是LIFO的。

 

 

Mutex變數是非0即1的,可看作一種資源的可用數量,初始化時Mutex是1,表示有一個可用資源,加鎖時獲得該資源,將Mutex減到0,表示不再有可用資源,解鎖時釋放該資源,將Mutex重新加到1,表示又有了一個可用資源。

 

訊號量(Semaphore)和Mutex類似,表示可用資源的數量,和Mutex不同的是這個數量可以大於1。

 

這裡介紹的是POSIX semaphore庫函式,詳見sem_overview(7),這種訊號量不僅可用於同一程式的執行緒間同步,也可用於不同程式間的同步。

 

#include <semaphore.h>

 

int sem_init(sem_t *sem, int pshared,unsigned int value);

int sem_wait(sem_t *sem);

int sem_trywait(sem_t *sem);

int sem_post(sem_t * sem);

int sem_destroy(sem_t * sem);

 

semaphore變數的型別為sem_t,sem_init()初始化一個semaphore變數,value參數列示可用資源的數量,pshared引數為0表示訊號量用於同一程式的執行緒間同步,本節只介紹這種情況。在用完semaphore變數之後應該呼叫sem_destroy()釋放與semaphore相關的資源。

 

呼叫sem_wait()可以獲得資源,使semaphore的值減1,如果呼叫sem_wait()時semaphore的值已經是0,則掛起等待。如果不希望掛起等待,可以呼叫sem_trywait()。呼叫sem_post()可以釋放資源,使semaphore的值加1,同時喚醒掛起等待的執行緒。

 

上面生產者-消費者的例子是基於連結串列的,其空間可以動態分配,現在基於固定大小的環形佇列重寫這個程式:

 

#include <stdlib.h>

#include <pthread.h>

#include <stdio.h>

#include <semaphore.h>

 

#define NUM 5

int queue[NUM];

sem_t blank_number, product_number;

 

void *producer(void *arg)

{

         intp = 0;

         while(1) {

                   sem_wait(&blank_number);

                   queue[p]= rand() % 1000 + 1;

                   printf("Produce%d\n", queue[p]);

                   sem_post(&product_number);

                   p= (p+1)%NUM;

                   sleep(rand()%5);

         }

}

 

void *consumer(void *arg)

{

         intc = 0;

         while(1) {

                   sem_wait(&product_number);

                   printf("Consume%d\n", queue[c]);

                   queue[c]= 0;

                   sem_post(&blank_number);

                   c= (c+1)%NUM;

                   sleep(rand()%5);

         }

}

 

int main(int argc, char *argv[])

{

         pthread_tpid, cid; 

 

         sem_init(&blank_number,0, NUM);

         sem_init(&product_number,0, 0);

         pthread_create(&pid,NULL, producer, NULL);

         pthread_create(&cid,NULL, consumer, NULL);

         pthread_join(pid,NULL);

         pthread_join(cid,NULL);

         sem_destroy(&blank_number);

         sem_destroy(&product_number);

         return0;

}

 

 

 

 

 

 

 

 

 

 

相關文章