Advertisement
Guest User

Untitled

a guest
Feb 9th, 2014
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <future>
  3. #include <vector>
  4. #include <cassert>
  5.  
  6. struct S {
  7.     bool on_main_thread = false;
  8.     int tasks_run_on_this_thread = 0;
  9.  
  10.     S() { std::cerr << "S ctor\n"; }
  11.     ~S() { std::cerr << "S dtor\n"; }
  12. };
  13.  
  14. thread_local S s;
  15.  
  16. int main()
  17. {
  18.   s.on_main_thread = true;
  19.  
  20.   std::vector<std::future<void>> v;
  21.  
  22.   const int task_count = 10;
  23.   for (int i=0; i<task_count; ++i) {
  24.     v.emplace_back(std::async([] {
  25.       assert(s.tasks_run_on_this_thread == 0 || s.on_main_thread);
  26.       ++s.tasks_run_on_this_thread;
  27.     }));
  28.   }
  29.                    
  30.   for (auto &&t : v) {
  31.     t.get();  
  32.   }
  33.   std::cout << "Tasks run asynchronously: " << task_count - s.tasks_run_on_this_thread << " (Should be this many + 1 ctors/dtors run)\n";
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement