1. 程式人生 > >linux下的多執行緒/多程序同步/通訊機制

linux下的多執行緒/多程序同步/通訊機制

while (1)  
    {  
        //這個mutex主要是用來保證pthread_cond_wait的併發性  
        pthread_mutex_lock(&mtx);  
        while (head == NULL)  
        {  
            //這個while要特別說明一下,單個pthread_cond_wait功能很完善,為何  
            //這裡要有一個while (head == NULL)呢?因為pthread_cond_wait裡的線  
            //程可能會被意外喚醒,如果這個時候head != NULL,則不是我們想要的情況。  
            //這個時候,應該讓執行緒繼續進入pthread_cond_wait  
            // pthread_cond_wait會先解除之前的pthread_mutex_lock鎖定的mtx,  
            //然後阻塞在等待對列裡休眠,直到再次被喚醒(大多數情況下是等待的條件成立  
            //而被喚醒,喚醒後,該程序會先鎖定先pthread_mutex_lock(&mtx);,再讀取資源  
            //用這個流程是比較清楚的  
            pthread_cond_wait(&cond, &mtx);  
            p = head;  
            head = head->n_next;  
            printf("Got %d from front of queue/n", p->n_number);  
            free(p);  
        }  
        pthread_mutex_unlock(&mtx); //臨界區資料操作完畢,釋放互斥鎖  
    }  

三、訊號量(sem)

如同程序一樣,執行緒也可以通過訊號量來實現通訊,雖然是輕量級的。訊號量函式的名字都以"sem_"打頭。執行緒使用的基本訊號量函式有四個。