[英]Improve multi thread communication?
這是線程#1上的代碼:
move = false;
//start thread #2
while(!move) Sleep(5);
//do stuff
線程2代碼:
//do stuff
move = true;
是否有更好的方法來等待移動的變化,例如,在網絡中讀取數據之前執行所謂的阻止操作?
使用C ++ 11? 使用std :: condition_variable。
你擁有的是一種方法。
還有其他可以使用的東西。 我想到了一些:
使用條件
條件是您可以在其中等待代碼的其他部分(線程) 發出信號(可以繼續)的條件
條件與互斥鎖相關
在您的代碼中:
線程#1
// start thread #2
mutex.acquire();
// You could check for an actual condition here if it
// is more complex than a true false.
condition.wait();
// If we're checking for a complex condition here
// we should re-evaluate in case it is not satisfied.
mutex.release();
線程#2
// do stuff
mutex.acquire();
condition.signal();
mutex.release();
使用未來
Future是用於表示異步操作結果的更高級別的構造。
它或多或少是這樣的:
Future
對象並保留對其的引用,並將引用傳遞給執行異步操作的線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.