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

0ve6wy6x  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(124)

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

  1. #include <chrono>
  2. #include <iostream>
  3. #include <thread>
  4. #include <latch>
  5. using namespace std::chrono_literals;
  6. std::latch latch{ 3 };
  7. std::latch taskDone{ 1 };
  8. void worker_f(int this_id)
  9. {
  10. if (latch.try_wait())
  11. {
  12. std::printf("worker %d comes late, full slot ... waiting for the task done\n", this_id);
  13. taskDone.wait();
  14. std::printf("task done, worker %d exit\n", this_id);
  15. }
  16. else
  17. {
  18. std::printf("worker %d comes on time, there is a task for him\n", this_id);
  19. latch.count_down();
  20. }
  21. std::this_thread::sleep_for(100ms);
  22. }
  23. int main()
  24. {
  25. for (int i = 0; i < 5; ++i)
  26. {
  27. std::jthread ac{ worker_f, i };
  28. }
  29. std::cout << "hello" << std::endl;
  30. std::printf("waiting for worker\n");
  31. latch.wait();
  32. std::printf("full slot, doing task\n");
  33. taskDone.count_down();
  34. std::printf("task done\n");
  35. std::this_thread::sleep_for(1000ms);
  36. }

字符串
输出:

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


非常感谢您的帮助!

vs3odd8k

vs3odd8k1#

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

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

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

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

展开查看全部

相关问题