brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.8 KiB · edebe94 Raw
74 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 detach();13 14#include <atomic>15#include <cassert>16#include <chrono>17#include <concepts>18#include <functional>19#include <optional>20#include <system_error>21#include <thread>22#include <type_traits>23 24#include "make_test_thread.h"25#include "test_macros.h"26 27int main(int, char**) {28  // Effects: The thread represented by *this continues execution without the calling thread blocking.29  {30    std::atomic_bool start{false};31    std::atomic_bool done{false};32    std::optional<std::jthread> jt = support::make_test_jthread([&start, &done] {33      start.wait(false);34      done = true;35    });36 37    // If it blocks, it will deadlock here38    jt->detach();39 40    jt.reset();41 42    // The other thread continues execution43    start = true;44    start.notify_all();45    while (!done) {46    }47  }48 49  // Postconditions: get_id() == id().50  {51    std::jthread jt = support::make_test_jthread([] {});52    assert(jt.get_id() != std::jthread::id());53    jt.detach();54    assert(jt.get_id() == std::jthread::id());55  }56 57#if !defined(TEST_HAS_NO_EXCEPTIONS)58  // Throws: system_error when an exception is required ([thread.req.exception]).59  // invalid_argument - if the thread is not joinable.60  {61    std::jthread jt;62    try {63      jt.detach();64      assert(false);65    } catch (const std::system_error& err) {66      assert(err.code() == std::errc::invalid_argument);67    }68  }69#endif70 71  std::this_thread::sleep_for(std::chrono::milliseconds{2});72  return 0;73}74