pthread_cond_wait() 用法深入分析
更新時(shí)間:2013年07月26日 08:42:46 作者:
以下是對(duì)pthread_cond_wait的用法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下
很久沒(méi)看APUE,今天一位朋友問(wèn)道關(guān)于一個(gè)mutex的問(wèn)題,又翻到了以前討論過(guò)的東西,為了不讓自己忘記,把曾經(jīng)的東西總結(jié)一下。
先大體看下網(wǎng)上很多地方都有的關(guān)于pthread_cond_wait()的說(shuō)明:
條件變量
條件變量是利用線程間共享的全局變量進(jìn)行同步的一種機(jī)制,主要包括兩個(gè)動(dòng)作:一個(gè)線程等待"條件變量的條件成立"而掛起;另一個(gè)線程使"條件成立"(給出條件成立信號(hào))。為了防止競(jìng)爭(zhēng),條件變量的使用總是和一個(gè)互斥鎖結(jié)合在一起。
1.創(chuàng)建和注銷
條件變量和互斥鎖一樣,都有靜態(tài)動(dòng)態(tài)兩種創(chuàng)建方式,靜態(tài)方式使用PTHREAD_COND_INITIALIZER常量,如下:
pthread_cond_t cond=PTHREAD_COND_INITIALIZER
動(dòng)態(tài)方式調(diào)用pthread_cond_init()函數(shù),API定義如下:
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr)
盡管POSIX標(biāo)準(zhǔn)中為條件變量定義了屬性,但在LinuxThreads中沒(méi)有實(shí)現(xiàn),因此cond_attr值通常為NULL,且被忽略。
注銷一個(gè)條件變量需要調(diào)用pthread_cond_destroy(),只有在沒(méi)有線程在該條件變量上等待的時(shí)候才能注銷這個(gè)條件變量,否則返回EBUSY。因?yàn)長(zhǎng)inux實(shí)現(xiàn)的條件變量沒(méi)有分配什么資源,所以注銷動(dòng)作只包括檢查是否有等待線程。API定義如下:
int pthread_cond_destroy(pthread_cond_t *cond)
2.等待和激發(fā)
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
等待條件有兩種方式:無(wú)條件等待pthread_cond_wait()和計(jì)時(shí)等待pthread_cond_timedwait(),其中計(jì)時(shí)等待方式如果在給定時(shí)刻前條件沒(méi)有滿足,則返回ETIMEOUT,結(jié)束等待,其中abstime以與time()系統(tǒng)調(diào)用相同意義的絕對(duì)時(shí)間形式出現(xiàn),0表示格林尼治時(shí)間1970年1月1日0時(shí)0分0秒。
無(wú)論哪種等待方式,都必須和一個(gè)互斥鎖配合,以防止多個(gè)線程同時(shí)請(qǐng)求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的競(jìng)爭(zhēng)條件(Race Condition)。mutex互斥鎖必須是普通鎖(PTHREAD_MUTEX_TIMED_NP)或者適應(yīng)鎖(PTHREAD_MUTEX_ADAPTIVE_NP),且在調(diào)用pthread_cond_wait()前必須由本線程加鎖(pthread_mutex_lock()),而在更新條件等待隊(duì)列以前,mutex保持鎖定狀態(tài),并在線程掛起進(jìn)入等待前解鎖。在條件滿足從而離開(kāi)pthread_cond_wait()之前,mutex將被重新加鎖,以與進(jìn)入pthread_cond_wait()前的加鎖動(dòng)作對(duì)應(yīng)。
激發(fā)條件有兩種形式,pthread_cond_signal()激活一個(gè)等待該條件的線程,存在多個(gè)等待線程時(shí)按入隊(duì)順序激活其中一個(gè);而pthread_cond_broadcast()則激活所有等待線程。
現(xiàn)在來(lái)看一段典型的應(yīng)用:看注釋即可。
#include <pthread.h>
#include <unistd.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node {
int n_number;
struct node *n_next;
} *head = NULL;
/*[thread_func]*/
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread./n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = NULL;
pthread_cleanup_push(cleanup_handler, p);
while (1) {
pthread_mutex_lock(&mtx); //這個(gè)mutex主要是用來(lái)保證pthread_cond_wait的并發(fā)性
while (head == NULL) { //這個(gè)while要特別說(shuō)明一下,單個(gè)pthread_cond_wait功能很完善,為何這里要有一個(gè)while (head == NULL)呢?因?yàn)閜thread_cond_wait里的線程可能會(huì)被意外喚醒,如果這個(gè)時(shí)候head != NULL,則不是我們想要的情況。這個(gè)時(shí)候,應(yīng)該讓線程繼續(xù)進(jìn)入pthread_cond_wait
pthread_cond_wait(&cond, &mtx); // pthread_cond_wait會(huì)先解除之前的pthread_mutex_lock鎖定的mtx,然后阻塞在等待對(duì)列里休眠,直到再次被喚醒(大多數(shù)情況下是等待的條件成立而被喚醒,喚醒后,該進(jìn)程會(huì)先鎖定先pthread_mutex_lock(&mtx);,再讀取資源
//用這個(gè)流程是比較清楚的/*block-->unlock-->wait() return-->lock*/
}
p = head;
head = head->n_next;
printf("Got %d from front of queue/n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx); //臨界區(qū)數(shù)據(jù)操作完畢,釋放互斥鎖
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, NULL, thread_func, NULL); //子線程會(huì)一直等待資源,類似生產(chǎn)者和消費(fèi)者,但是這里的消費(fèi)者可以是多個(gè)消費(fèi)者,而不僅僅支持普通的單個(gè)消費(fèi)者,這個(gè)模型雖然簡(jiǎn)單,但是很強(qiáng)大
/*[tx6-main]*/
for (i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx); //需要操作head這個(gè)臨界資源,先加鎖,
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx); //解鎖
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2./n");
pthread_cancel(tid); //關(guān)于pthread_cancel,有一點(diǎn)額外的說(shuō)明,它是從外部終止子線程,子線程會(huì)在最近的取消點(diǎn),退出線程,而在我們的代碼里,最近的取消點(diǎn)肯定就是pthread_cond_wait()了。關(guān)于取消點(diǎn)的信息,有興趣可以google,這里不多說(shuō)了
pthread_join(tid, NULL);
printf("All done -- exiting/n");
return 0;
}
先大體看下網(wǎng)上很多地方都有的關(guān)于pthread_cond_wait()的說(shuō)明:
條件變量
條件變量是利用線程間共享的全局變量進(jìn)行同步的一種機(jī)制,主要包括兩個(gè)動(dòng)作:一個(gè)線程等待"條件變量的條件成立"而掛起;另一個(gè)線程使"條件成立"(給出條件成立信號(hào))。為了防止競(jìng)爭(zhēng),條件變量的使用總是和一個(gè)互斥鎖結(jié)合在一起。
1.創(chuàng)建和注銷
條件變量和互斥鎖一樣,都有靜態(tài)動(dòng)態(tài)兩種創(chuàng)建方式,靜態(tài)方式使用PTHREAD_COND_INITIALIZER常量,如下:
復(fù)制代碼 代碼如下:
pthread_cond_t cond=PTHREAD_COND_INITIALIZER
動(dòng)態(tài)方式調(diào)用pthread_cond_init()函數(shù),API定義如下:
復(fù)制代碼 代碼如下:
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr)
盡管POSIX標(biāo)準(zhǔn)中為條件變量定義了屬性,但在LinuxThreads中沒(méi)有實(shí)現(xiàn),因此cond_attr值通常為NULL,且被忽略。
注銷一個(gè)條件變量需要調(diào)用pthread_cond_destroy(),只有在沒(méi)有線程在該條件變量上等待的時(shí)候才能注銷這個(gè)條件變量,否則返回EBUSY。因?yàn)長(zhǎng)inux實(shí)現(xiàn)的條件變量沒(méi)有分配什么資源,所以注銷動(dòng)作只包括檢查是否有等待線程。API定義如下:
復(fù)制代碼 代碼如下:
int pthread_cond_destroy(pthread_cond_t *cond)
2.等待和激發(fā)
復(fù)制代碼 代碼如下:
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
等待條件有兩種方式:無(wú)條件等待pthread_cond_wait()和計(jì)時(shí)等待pthread_cond_timedwait(),其中計(jì)時(shí)等待方式如果在給定時(shí)刻前條件沒(méi)有滿足,則返回ETIMEOUT,結(jié)束等待,其中abstime以與time()系統(tǒng)調(diào)用相同意義的絕對(duì)時(shí)間形式出現(xiàn),0表示格林尼治時(shí)間1970年1月1日0時(shí)0分0秒。
無(wú)論哪種等待方式,都必須和一個(gè)互斥鎖配合,以防止多個(gè)線程同時(shí)請(qǐng)求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的競(jìng)爭(zhēng)條件(Race Condition)。mutex互斥鎖必須是普通鎖(PTHREAD_MUTEX_TIMED_NP)或者適應(yīng)鎖(PTHREAD_MUTEX_ADAPTIVE_NP),且在調(diào)用pthread_cond_wait()前必須由本線程加鎖(pthread_mutex_lock()),而在更新條件等待隊(duì)列以前,mutex保持鎖定狀態(tài),并在線程掛起進(jìn)入等待前解鎖。在條件滿足從而離開(kāi)pthread_cond_wait()之前,mutex將被重新加鎖,以與進(jìn)入pthread_cond_wait()前的加鎖動(dòng)作對(duì)應(yīng)。
激發(fā)條件有兩種形式,pthread_cond_signal()激活一個(gè)等待該條件的線程,存在多個(gè)等待線程時(shí)按入隊(duì)順序激活其中一個(gè);而pthread_cond_broadcast()則激活所有等待線程。
現(xiàn)在來(lái)看一段典型的應(yīng)用:看注釋即可。
復(fù)制代碼 代碼如下:
#include <pthread.h>
#include <unistd.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node {
int n_number;
struct node *n_next;
} *head = NULL;
/*[thread_func]*/
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread./n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = NULL;
pthread_cleanup_push(cleanup_handler, p);
while (1) {
pthread_mutex_lock(&mtx); //這個(gè)mutex主要是用來(lái)保證pthread_cond_wait的并發(fā)性
while (head == NULL) { //這個(gè)while要特別說(shuō)明一下,單個(gè)pthread_cond_wait功能很完善,為何這里要有一個(gè)while (head == NULL)呢?因?yàn)閜thread_cond_wait里的線程可能會(huì)被意外喚醒,如果這個(gè)時(shí)候head != NULL,則不是我們想要的情況。這個(gè)時(shí)候,應(yīng)該讓線程繼續(xù)進(jìn)入pthread_cond_wait
pthread_cond_wait(&cond, &mtx); // pthread_cond_wait會(huì)先解除之前的pthread_mutex_lock鎖定的mtx,然后阻塞在等待對(duì)列里休眠,直到再次被喚醒(大多數(shù)情況下是等待的條件成立而被喚醒,喚醒后,該進(jìn)程會(huì)先鎖定先pthread_mutex_lock(&mtx);,再讀取資源
//用這個(gè)流程是比較清楚的/*block-->unlock-->wait() return-->lock*/
}
p = head;
head = head->n_next;
printf("Got %d from front of queue/n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx); //臨界區(qū)數(shù)據(jù)操作完畢,釋放互斥鎖
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, NULL, thread_func, NULL); //子線程會(huì)一直等待資源,類似生產(chǎn)者和消費(fèi)者,但是這里的消費(fèi)者可以是多個(gè)消費(fèi)者,而不僅僅支持普通的單個(gè)消費(fèi)者,這個(gè)模型雖然簡(jiǎn)單,但是很強(qiáng)大
/*[tx6-main]*/
for (i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx); //需要操作head這個(gè)臨界資源,先加鎖,
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx); //解鎖
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2./n");
pthread_cancel(tid); //關(guān)于pthread_cancel,有一點(diǎn)額外的說(shuō)明,它是從外部終止子線程,子線程會(huì)在最近的取消點(diǎn),退出線程,而在我們的代碼里,最近的取消點(diǎn)肯定就是pthread_cond_wait()了。關(guān)于取消點(diǎn)的信息,有興趣可以google,這里不多說(shuō)了
pthread_join(tid, NULL);
printf("All done -- exiting/n");
return 0;
}
相關(guān)文章
C++實(shí)現(xiàn)一個(gè)簡(jiǎn)單消息隊(duì)列的示例詳解
消息隊(duì)列在多線程的場(chǎng)景有時(shí)會(huì)用到,尤其是線程通信跨線程調(diào)用的時(shí)候,就可以使用消息隊(duì)列進(jìn)行通信。本文將利用C++實(shí)現(xiàn)一個(gè)簡(jiǎn)單的消息隊(duì)列,感興趣的可以了解一下2022-12-12
VisualStudio?禁用移動(dòng)文件到文件夾自動(dòng)修改命名空間功能
這篇文章主要介紹了VisualStudio?禁用移動(dòng)文件到文件夾自動(dòng)修改命名空間功能,文章底部給大家介紹了解決安裝VS2022時(shí),出現(xiàn)未能安裝包“Microsoft.VisualCpp.Redist.14,version=14.32.31332,chip”=x86,的問(wèn)題及解決方法,需要的朋友可以參考下2022-09-09
C語(yǔ)言棧與隊(duì)列相互實(shí)現(xiàn)詳解
棧和隊(duì)列,嚴(yán)格意義上來(lái)說(shuō),也屬于線性表,因?yàn)樗鼈円捕加糜诖鎯?chǔ)邏輯關(guān)系為 "一對(duì)一" 的數(shù)據(jù),但由于它們比較特殊,本章講解分別用隊(duì)列實(shí)現(xiàn)棧與用棧實(shí)現(xiàn)隊(duì)列2022-04-04
C/C++ break和continue區(qū)別及使用方法
這篇文章主要介紹了C/C++ break和continue區(qū)別及使用方法的相關(guān)資料,需要的朋友可以參考下2017-07-07
淺析c#中如何在form的webbrowser控件中獲得鼠標(biāo)坐標(biāo)
以下是對(duì)c#中如何在form的webbrowser控件中獲得鼠標(biāo)坐標(biāo)的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以參考下2013-07-07
Qt采用線程以隊(duì)列方式實(shí)現(xiàn)下發(fā)數(shù)據(jù)
在C++中隊(duì)列是一種常用的數(shù)據(jù)結(jié)構(gòu)之一,一種特殊的線性表,一般采用先進(jìn)先出的方式。本文主要為大家介紹了Qt如何以隊(duì)列方式實(shí)現(xiàn)下發(fā)數(shù)據(jù),感興趣的可以了解一下2022-10-10
基于matlab MFCC+GMM的安全事件聲學(xué)檢測(cè)系統(tǒng)
這篇文章主要為大家介紹了基于matlab MFCC+GMM的安全事件聲學(xué)檢測(cè)系統(tǒng)實(shí)現(xiàn)及源碼示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-02-02

