88 lines · cpp
1//===----------------------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// UNSUPPORTED: no-threads10// UNSUPPORTED: c++03, c++11, c++14, c++1711 12// void join();13 14#include <atomic>15#include <cassert>16#include <chrono>17#include <concepts>18#include <functional>19#include <system_error>20#include <thread>21#include <type_traits>22#include <vector>23 24#include "make_test_thread.h"25#include "test_macros.h"26 27int main(int, char**) {28 // Effects: Blocks until the thread represented by *this has completed.29 {30 std::atomic_int calledTimes = 0;31 std::vector<std::jthread> jts;32 constexpr auto numberOfThreads = 10u;33 jts.reserve(numberOfThreads);34 for (auto i = 0u; i < numberOfThreads; ++i) {35 jts.emplace_back(support::make_test_jthread([&] {36 std::this_thread::sleep_for(std::chrono::milliseconds(2));37 calledTimes.fetch_add(1, std::memory_order_relaxed);38 }));39 }40 41 for (auto i = 0u; i < numberOfThreads; ++i) {42 jts[i].join();43 }44 45 // If join did block, calledTimes must equal to numberOfThreads46 // If join did not block, there is a chance that the check below happened47 // before test threads incrementing the counter, thus calledTimed would48 // be less than numberOfThreads.49 // This is not going to catch issues 100%. Creating more threads to increase50 // the probability of catching the issue51 assert(calledTimes.load(std::memory_order_relaxed) == numberOfThreads);52 }53 54 // Synchronization: The completion of the thread represented by *this synchronizes with55 // ([intro.multithread]) the corresponding successful join() return.56 {57 bool flag = false;58 std::jthread jt = support::make_test_jthread([&] { flag = true; });59 jt.join();60 assert(flag); // non atomic write is visible to the current thread61 }62 63 // Postconditions: The thread represented by *this has completed. get_id() == id().64 {65 std::jthread jt = support::make_test_jthread([] {});66 assert(jt.get_id() != std::jthread::id());67 jt.join();68 assert(jt.get_id() == std::jthread::id());69 }70 71#if !defined(TEST_HAS_NO_EXCEPTIONS)72 // Throws: system_error when an exception is required ([thread.req.exception]).73 // invalid_argument - if the thread is not joinable.74 {75 std::jthread jt;76 try {77 jt.join();78 assert(false);79 } catch (const std::system_error& err) {80 assert(err.code() == std::errc::invalid_argument);81 }82 }83 84#endif85 86 return 0;87}88