2016-03-24 63 views
0

我想寫一個程序,將不斷運行在一個循環內,只有在前一個線程已關閉時才運行線程。我無法檢查第一個if語句之外的線程狀態,因爲status是在第一個if語句內聲明的。如果我檢查第一條語句中的狀態,我會完全鎖定。我怎樣才能實現一些東西來解決這個問題,而不是讓線程加入主程序?線程執行內循環鎖

int script_lock = 1; //lock is open 
    while (true) { 

     if (script_lock == 1) { 
      script_lock = 0; //lock is closed 
      auto future = async (script, execute); //runs concurrently with main program 
      auto status = future.wait_for(chrono::milliseconds(0));  
     } 

     if (status == future_status::ready) { //status not declared in scope 
      script_lock = 1; //lock is open 
     } 

     //do extra stuff 
    } 
+0

你就不能後'while'聲明'status'權:

如下您可以簡化代碼? – 4386427

回答

0

此代碼有一個問題:如果script_lock等於0並在第一時間status == future_status::ready失敗,那麼script_lock永遠不會改變的價值。

bool finished = true; 
while (true) { 
    // Define future here 

    if (finished){ 
     future = async (script, execute); 
     finished = false; 
    } 

    if (future.wait_for(chrono::milliseconds(0)) == future_status::ready) 
      finished = true; 

    //do extra stuff 
} 
+0

'錯誤:'。'之前缺少模板參數。' if(future.wait_for(chrono :: milliseconds(0))== future_status :: ready)' –

+0

是的,你必須找出未來的完整類型沒有'auto',因爲它是在調用'async'之前定義的),並根據需要添加適當的模板參數。 – Claudio