日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux操作系统之条件变量

發(fā)布時間:2023/11/30 linux 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux操作系统之条件变量 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

(1)條件變量

? ? ? ? ? ? ? ?條件變量本身不是鎖,但它可以造成線程阻塞,通常與互斥鎖配合使用。

(2)條件鎖相關函數(shù)

? ? ? ? ? ? ? pthread_cond_t類型,用于定義條件變量

? ? ? ? ?1)初始化一個條件變量:pthread_cond_init

? ? ? ? ? ? ? ? ?int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);

? ? ? ? ? ? ? ?參數(shù)2:條件變量的屬性,傳NULL即可,為默認值

? ? ? ? ? ? ? ?可采用靜態(tài)初始化:pthread _cond_t cond=PTHREAD_COND_INITIALIZER;

? ? ? ? ?2)銷毀一個條件變量:pthread_cond_destroy

? ? ? ? ? ? ? ? int pthread_cond_destroy(pthread_cond_t *cond);

? ? ? ? ?3)阻塞等待條件變量:pthread_cond_wait(配合互斥鎖使用)

? ? ? ? ? ? ? ? int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);

? ? ? ? ? ? ? ? 函數(shù)作用:?

? ? ? ? ? ? ? ? ? ? ? ? ? ?1>阻塞等待條件變量cond滿足。

? ? ? ? ? ? ? ? ? ? ? ? ? ?2>釋放已掌握的互斥鎖(解鎖互斥量)相當于pthread_mutex_unlock(&mutex);?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?第1,2步為一個原子操作

? ? ? ? ? ? ? ? ? ? ? ? ? 3>當被喚醒,pthread_cond_wait函數(shù)返回,解除阻塞并重新獲得互斥鎖pthread_mutex_lock(&mutex)

? ? ? ?? 4)限時等待一個條件變量(以絕對時間等待):pthread_cond_timewait

? ? ? ? ? ? ? ? int pthread_cond_timewait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,condt struct timespec*restrcit abstime);

? ? ? ? ? ? ?struct timespec{

? ? ? ? ? ? ? ? ? ? ? ? ? time_t tv_sec;//秒

? ? ? ? ? ? ? ? ? ? ? ? ?long? ? tv_nsec;//納秒

? ? ? ? ? ? ? };

?abstime;絕對時間,通過time(NULL)函數(shù)獲取;

? ? ? ? ? 5)喚醒至少一個阻塞在條件變量上的線程:pthread_cond_signal

? ? ? ? ? ? ? ?int pthread_cond_signal(pthread_cond_t *cond);

? ? ? ? 6)喚醒全部阻塞在條件變量上的線程:pthread_cond_broadcast(pthread_cond_t? *cond);

(3)線程同步之生產者消費者變量模型

? ? ? ? ? 假定有兩個線程,一個模擬生產者行為,一個模擬消費者行為。兩個線程同時操作一個共享資源(匯聚),生產者生產產品,消費者消費產品。

? ? ? ??

? ? ? ?

? ? ? ? ? ? ? ??

?

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結

以上是生活随笔為你收集整理的linux操作系统之条件变量的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。