| 1 | // { dg-do run { target c++20 } } |
| 2 | // { dg-additional-options "-pthread" { target pthread } } |
| 3 | // { dg-require-gthreads "" } |
| 4 | // { dg-add-options libatomic } |
| 5 | |
| 6 | #include <iostream> |
| 7 | #include <sstream> |
| 8 | |
| 9 | #include <thread> |
| 10 | #include <semaphore> |
| 11 | #include <mutex> |
| 12 | #include <chrono> |
| 13 | #include <vector> |
| 14 | |
| 15 | std::counting_semaphore<4> semaphore{6}; |
| 16 | |
| 17 | std::mutex mtx; |
| 18 | std::vector<std::string> results; |
| 19 | |
| 20 | void thread_main(size_t x) |
| 21 | { |
| 22 | semaphore.acquire(); |
| 23 | std::this_thread::sleep_for(std::chrono::milliseconds(100)); |
| 24 | semaphore.release(); |
| 25 | { |
| 26 | std::ostringstream stm; |
| 27 | stm << "Thread " << x << " finished."; |
| 28 | std::lock_guard g{ mtx }; |
| 29 | results.push_back(stm.str()); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | int main() |
| 34 | { |
| 35 | constexpr auto nthreads = 10; |
| 36 | |
| 37 | std::vector<std::thread> threads(nthreads); |
| 38 | |
| 39 | size_t counter{0}; |
| 40 | for(auto& t : threads) |
| 41 | { |
| 42 | t = std::thread(thread_main, counter++); |
| 43 | } |
| 44 | |
| 45 | for(auto& t : threads) |
| 46 | { |
| 47 | t.join(); |
| 48 | { |
| 49 | std::lock_guard g{ mtx }; |
| 50 | for (auto&& r : results) |
| 51 | std::cout << r << '\n'; |
| 52 | std::cout.flush(); |
| 53 | results.clear(); |
| 54 | } |
| 55 | } |
| 56 | } |