jack06215

[tutorial] Async callback

Jul 17th, 2020 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <atomic>
  2. #include <chrono>
  3. #include <deque>
  4. #include <iostream>
  5. #include <mutex>
  6. #include <future>
  7. #include <thread>
  8.  
  9. // shared stuff:
  10. std::deque<std::packaged_task<void()>> tasks;
  11. std::mutex tasks_mutex;
  12. std::atomic<bool> gui_running;
  13.  
  14. void message() {
  15.     std::cout << std::this_thread::get_id() << std::endl;
  16. }
  17.  
  18. void one_off()
  19. {
  20.     std::packaged_task<void()> task(message);
  21.     std::future<void> result = task.get_future();
  22.     {
  23.         std::lock_guard<std::mutex> lock(tasks_mutex);
  24.         tasks.push_back(std::move(task));
  25.     }
  26.     // wait on result
  27.     result.get();
  28. }
  29.  
  30. void gui_thread()
  31. {
  32.     std::cout << "gui thread: "; message();
  33.  
  34.     while (gui_running) { // process messages
  35.  
  36.         {
  37.             std::unique_lock<std::mutex> lock(tasks_mutex);
  38.             while (!tasks.empty()) {
  39.                 auto task(std::move(tasks.front()));
  40.                 tasks.pop_front();
  41.  
  42.                 // unlock during the task
  43.                 lock.unlock();
  44.                 task();
  45.                 lock.lock();
  46.             }
  47.         }
  48.         // pretend you are doing "gui work"
  49.         std::this_thread::sleep_for(std::chrono::milliseconds(100));
  50.     }
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56.     gui_running = true;
  57.  
  58.     std::cout << "main thread: "; message();
  59.     std::thread gt(gui_thread);
  60.  
  61.     for (unsigned i = 0; i < 5; ++i) {
  62.         // note: these will be launched sequentially because result's
  63.         // destructor will block until one_off completes
  64.         std::async(std::launch::async, one_off);
  65.     }
  66.  
  67.     // the for loop will not complete until all the tasks have been
  68.     // processed by gui_thread
  69.  
  70.     // ...
  71.  
  72.     // cleanup
  73.     gui_running = false;
  74.     gt.join();
  75. }
Add Comment
Please, Sign In to add comment