2016-03-24 54 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