多執行緒程式設計介紹 條件變數

2021-09-14 05:51:13 字數 1693 閱讀 8565

條件變數是多執行緒對共享資源資料的變化的通知機制。條件變數與互斥量明顯不同為互斥量是對臨界資源的保護機制,但條件變數可以理解為一種通訊機制。

設想如下程式設計場景,我們要實現乙個訊息接收**並處理的流程,為了提高程式執行效率。我們啟動兩個執行緒乙個是接收訊息執行緒,專門負責接收訊息,將訊息加入到乙個共享鍊錶中;而乙個執行緒是工作執行緒,專門負責等待讀取鍊錶中的訊息,如果鍊錶為空,則工作執行緒則進入等待佇列,如果有節點插入則工作執行緒需要被喚醒繼續工作。

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
#include #include #include #include #define msg_len_max        31

typedef struct tagnode

node_s;

typedef struct taglist

list_s;

list_s g_stmsglist = {};

void list_init(list_s *pstlist)

/*工作執行緒用於處理並列印訊息*/

void * dealmsgthread(void * pvoid)

if ( null != g_stmsglist.sthead.pstnextnode )

pthread_mutex_unlock(&g_stmsglist.mutex);

if ( count >= 10 )

}return null;

}/*向訊息佇列中放入節點,並通知等待的工執行緒*/

void receivemsg(char *pcmsg, int ilen)

pstnode = (node_s*)malloc(sizeof(node_s));

memset(pstnode, 0, sizeof(node_s));

snprintf(pstnode->szmsg, msg_len_max+1, "%s", pcmsg);

/* 獲取鎖 */

pthread_mutex_lock(&g_stmsglist.mutex);

psttemp = &g_stmsglist.sthead;

while ( psttemp )

psttemp = psttemp->pstnextnode;

}psttemp->pstnextnode = pstnode;

printf("recieve msg %s add list, send signal\n", pcmsg);

/* 傳送通知到工作執行緒 */

pthread_cond_signal(&g_stmsglist.cond);

pthread_mutex_unlock(&g_stmsglist.mutex);

return;

}/*main函式*/

int main(int argc, char **ar**)

pthread_join(ithreadid, &ret);

return 0;

}

1.條件變數內部猜想一:條件變數pthread_cond_timedwait函式內部對於條件變數本身還存在乙個鎖。

pthread_cond_signal函式在mutex lock,unlock之後執行。

多執行緒程式設計 條件變數

條件變數 條件變數是利用執行緒間共享的全域性變數進行同步的一種機制,主要包括兩個動作 乙個執行緒等待 條件變數的條件成立 而掛起 另乙個執行緒使 條件成立 給出條件成立訊號 為了防止競爭,條件變數的使用總是和乙個互斥鎖結合在一起。1.建立和登出 條件變數和互斥鎖一樣,都有靜態和動態兩種建立方式,靜態...

多執行緒程式設計 條件變數

include include include include 靜態方式初始化乙個互斥鎖和乙個條件變數 static pthread mutex t mutex pthread mutex initializer static pthread cond t cond pthread cond ini...

多執行緒程式設計 條件變數

自 1 引言 條件變數是一種同步機制,允許執行緒掛起,直到共享資料上的某些條件得到滿足。條件變數上的基本操作有 觸發條件 當條件變為true 時 等待條件,掛起執行緒直到其他執行緒觸發條件。條件變數要和互斥量相聯結,以避免出現條件競爭 乙個執行緒預備等待乙個條件變數,當它在真正進入等待之前,另乙個執...