同步併發操作之等待乙個事件或條件

2021-06-26 10:24:28 字數 1332 閱讀 5180

兩個執行緒需要同步操作時,可以設定乙個全域性變數,用互斥量保護這個全域性變數,通過這個全域性變數來同步。

但是這樣太浪費cpu,這時可以用休眠方法。

bool flag;

std::mutex m;

void wait_for_flag()

}

但是很難確定休眠時間的長短,太長或太短都不合理。

在c++庫中,可以使用條件變數(condition variable)。條件變數可以和事件或條件結合起來,乙個或多個執行緒等待時間或條件。當事件到達貨事件滿足後,使用nofify通知等待的執行緒。

下面看乙個例子,生產者號消費者:

#include#include#include#include#include#include//vs2013除錯用的

std::mutex mut;

std::queueq;

std::condition_variable cond;

void data_preparation_thread()

}void data_processing_thread()

);//lambda function,等待的條件

int data = q.front();

q.pop();

lk.unlock();

std::cout << "processing data:" << data << std::endl; }}

int main()

下面使用條件變數編寫乙個執行緒安全的佇列

#include#include#include#includetemplateclass threadsafe_queue

threadsafe_queue(threadsafe_queue const& other)

void push(t new_value)

void wait_and_pop(t& value)

); valuue = data_queue.front();

data_queue.pop();

} std::shared_ptrwait_and_pop()

); std::shared_ptrres(std::make_shared(data_queue.front()));

data_queue.pop();

return res;

} bool try_pop(t& value)

std::shared_ptrtry_pop()

bool empty() const

};

同步併發操作之等待一次性事件

有時候需要用一些後台執行緒來完成計算,這些計算往往都是一次性的,執行緒計算完後便結束。這時候可以使用條件變數,但是有點浪費,我們只需要獲取一次結果。c 標準庫中有標頭檔案,很形象 未來 獲取未來計算的結果。使用std async來啟動乙個非同步任務。用std future物件來儲存非同步任務返回的結...

參考瀏覽器事件派發實現乙個同步事件流

同步事件流 在函式中可以終止該階段後續函式的執行,也可以終止整個流程 同步流程控制 function syncprocess hooks syncprocess.prototype.run function initdata,inithook var listeners this.listeners...

每日一條JS精華片段 建立乙個發布 訂閱 事件器

建立乙個發布 訂閱事件器,擁有emit,on和off方法。const createeventhub on event,handler off event,handler const handler data console.log data const hub createeventhub let ...