【问题标题】:Thread execution inside loop with locks带锁的循环内线程执行
【发布时间】:2023-03-10 16:32:02
【问题描述】:

我正在尝试编写一个程序,该程序将在循环中不断运行,并且仅在前一个线程已关闭时才运行一个线程。我无法在第一个 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
    }

【问题讨论】:

  • 你不能在while 之后声明status 吗?

标签: c++ multithreading pthreads


【解决方案1】:

这段代码有一个问题:如果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
}

【讨论】:

  • error: missing template arguments before ‘.’ token if (future.wait_for(chrono::milliseconds(0)) == future_status::ready)
  • 是的,你必须弄清楚未来的完整类型(不是auto,因为它是在调用async之前定义的)并在需要时添加适当的模板参数。
猜你喜欢
  • 2021-03-14
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多