69 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// ~jthread();13 14#include <atomic>15#include <cassert>16#include <optional>17#include <stop_token>18#include <thread>19#include <type_traits>20#include <vector>21 22#include "make_test_thread.h"23#include "test_macros.h"24 25int main(int, char**) {26 // !joinable()27 {28 std::jthread jt;29 assert(!jt.joinable());30 }31 32 // If joinable() is true, calls request_stop() and then join().33 // request_stop is called34 {35 std::optional<std::jthread> jt = support::make_test_jthread([] {});36 bool called = false;37 std::stop_callback cb(jt->get_stop_token(), [&called] { called = true; });38 jt.reset();39 assert(called);40 }41 42 // If joinable() is true, calls request_stop() and then join().43 // join is called44 {45 std::atomic_int calledTimes = 0;46 std::vector<std::jthread> jts;47 48 constexpr auto numberOfThreads = 10u;49 jts.reserve(numberOfThreads);50 for (auto i = 0u; i < numberOfThreads; ++i) {51 jts.emplace_back(support::make_test_jthread([&calledTimes] {52 std::this_thread::sleep_for(std::chrono::milliseconds{2});53 calledTimes.fetch_add(1, std::memory_order_relaxed);54 }));55 }56 jts.clear();57 58 // If join was called as expected, calledTimes must equal to numberOfThreads59 // If join was not called, there is a chance that the check below happened60 // before test threads incrementing the counter, thus calledTimed would61 // be less than numberOfThreads.62 // This is not going to catch issues 100%. Creating more threads would increase63 // the probability of catching the issue64 assert(calledTimes.load(std::memory_order_relaxed) == numberOfThreads);65 }66 67 return 0;68}69