alaestor

[C++] quick and dirty object multithread example

Jun 9th, 2022 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1.  
  2. /// Honshitsu#9218
  3.  
  4. #include <vector>
  5. #include <thread>
  6.  
  7. template <class T>
  8. requires requires (T t){ { t.run() }; }
  9. auto multithread(std::size_t thread_count, T& t)
  10. {
  11.     std::vector<std::jthread> threads;
  12.     threads.reserve(thread_count);
  13.     for (std::size_t i{}; i < thread_count; ++i)
  14.         threads.push_back(std::jthread{ &T::run, &t });
  15.     return threads;
  16. }
  17.  
  18. #include <iostream>
  19. #include <atomic>
  20. #include <mutex>
  21.  
  22. struct S
  23. {
  24.     std::mutex mutex;
  25.     unsigned int i{};
  26.  
  27.     void run()
  28.     {
  29.         std::lock_guard lock{ mutex };
  30.         std::cout << i++ << std::endl;
  31.     }
  32. };
  33.  
  34. int main()
  35. {
  36.     S s;
  37.     auto threads{ multithread(5, s) };
  38.  
  39.     for (auto& thread : threads)
  40.         thread.join(); // redundant
  41. }
Add Comment
Please, Sign In to add comment