fork download
  1. #include <iostream>
  2. #include <future>
  3. #include <condition_variable>
  4. #include <vector>
  5.  
  6. using namespace std::chrono_literals;
  7.  
  8. std::shared_future<void> ready;
  9.  
  10. std::mutex finish_mx;
  11. std::condition_variable finish_cv;
  12.  
  13. int execute(int val, const std::shared_future<void> &ready){
  14. ready.wait();
  15.  
  16. std::lock_guard<std::mutex> lock(finish_mx);
  17. std::cout<<"Locked: "<<val<<std::endl;
  18. finish_cv.notify_one();
  19.  
  20. return val;
  21. }
  22.  
  23.  
  24. int main()
  25. {
  26. std::promise<void> promise;
  27. auto shared = promise.get_future().share();
  28.  
  29. std::vector<std::future<int>> pool;
  30. for (int i=0; i<10; ++i){
  31. auto fut = std::async(std::launch::async, execute, i, std::cref(shared));
  32. pool.push_back(std::move(fut));
  33. }
  34.  
  35. std::this_thread::sleep_for(100ms);
  36.  
  37. std::unique_lock<std::mutex> finish_lock(finish_mx);
  38. promise.set_value();
  39.  
  40. for (int i=0; pool.size() > 0; ++i)
  41. {
  42. finish_cv.wait(finish_lock);
  43. std::cout<<"Notifies: "<<i<<std::endl;
  44.  
  45. for (auto it = pool.begin(); it != pool.end(); ++it) {
  46. auto state = it->wait_for(0ms);
  47. if (state == std::future_status::ready) {
  48. pool.erase(it);
  49. break;
  50. }
  51. }
  52. }
  53. }
Time limit exceeded #stdin #stdout 5s 102144KB
stdin
Standard input is empty
stdout
Locked: 6
Locked: 7
Locked: 8
Locked: 9
Locked: 5
Locked: 4
Locked: 3
Locked: 2
Locked: 1
Notifies: 0
Locked: 0
Notifies: 1