带锁的循环内部线程执行

时间:2016-03-24 07:41:19

标签: c++ multithreading pthreads

我正在尝试编写一个程序,该程序将在循环内不断运行,并且只有在前一个线程关闭时才运行一个线程。我无法在第一个if语句之外检查线程的状态,因为在第一个if语句中声明了status。如果我检查第一个语句中的状态,我会被完全锁定。如何在不使线程加入主程序的情况下实现某些功能?

    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
    }

1 个答案:

答案 0 :(得分: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
}