std::latch C++20 latch.wait()阻塞整个程序

0ve6wy6x  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(93)

我正在学习C++20,并尝试练习std::latch
但是我的例子不太好用,你能帮我调试一下这个代码吗?
我的程序在调用taskDone.wait()函数时被阻塞

#include <chrono>
#include <iostream>
#include <thread>
#include <latch>

using namespace std::chrono_literals;
std::latch  latch{ 3 };
std::latch taskDone{ 1 };

void worker_f(int this_id)
{
    if (latch.try_wait())
    {
        std::printf("worker %d comes late, full slot ... waiting for the task done\n", this_id);
        taskDone.wait();
        std::printf("task done, worker %d exit\n", this_id);
    }
    else
    {
        std::printf("worker %d comes on time, there is a task for him\n", this_id);
        latch.count_down();
    }
    std::this_thread::sleep_for(100ms);
}
    

int main()
{
    for (int i = 0; i < 5; ++i)
    {
        std::jthread ac{ worker_f, i };
    }
    std::cout << "hello" << std::endl;
    std::printf("waiting for worker\n");
    latch.wait();
    std::printf("full slot, doing task\n");

    taskDone.count_down();
    
    std::printf("task done\n");
    std::this_thread::sleep_for(1000ms);
}

字符串
输出:

worker 0 comes on time, there is a task for him
worker 1 comes on time, there is a task for him
worker 2 comes on time, there is a task for him
worker 3 comes late, full slot ... waiting for the task done


非常感谢您的帮助!

vs3odd8k

vs3odd8k1#

你的问题是你的线程没有并行运行:

for (int i = 0; i < 5; ++i) {
    std::jthread ac{ worker_f, i };
}

字符串
ac是一个局部变量,在其作用域结束时(下一个循环开始时)被销毁。当std::jthread被销毁时,它等待其线程通过ac.request_stop(); ac.join();加入。
这意味着您正在启动一个线程,并等待它结束,然后再继续循环的下一次迭代。
您需要将它们移出范围:

std::jthread acs[5];
for (int i = 0; i < 5; ++i) {
    acs[i] = std::jthread{ worker_f, i };
}

相关问题