Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Honshitsu#9218
- #include <vector>
- #include <thread>
- template <class T>
- requires requires (T t){ { t.run() }; }
- auto multithread(std::size_t thread_count, T& t)
- {
- std::vector<std::jthread> threads;
- threads.reserve(thread_count);
- for (std::size_t i{}; i < thread_count; ++i)
- threads.push_back(std::jthread{ &T::run, &t });
- return threads;
- }
- #include <iostream>
- #include <atomic>
- #include <mutex>
- struct S
- {
- std::mutex mutex;
- unsigned int i{};
- void run()
- {
- std::lock_guard lock{ mutex };
- std::cout << i++ << std::endl;
- }
- };
- int main()
- {
- S s;
- auto threads{ multithread(5, s) };
- for (auto& thread : threads)
- thread.join(); // redundant
- }
Add Comment
Please, Sign In to add comment