brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.7 KiB · fec8740 Raw
70 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 11// <mutex>12 13// Make sure std::unique_lock works with std::mutex as expected.14 15#include <atomic>16#include <cassert>17#include <mutex>18 19#include "make_test_thread.h"20 21std::atomic<bool> keep_waiting;22std::atomic<bool> child_thread_locked;23std::mutex mux;24bool main_thread_unlocked  = false;25bool child_thread_unlocked = false;26 27void lock_thread() {28  std::unique_lock<std::mutex> lock(mux);29  assert(main_thread_unlocked);30  main_thread_unlocked  = false;31  child_thread_unlocked = true;32}33 34void try_lock_thread() {35  std::unique_lock<std::mutex> lock(mux, std::try_to_lock_t());36  assert(lock.owns_lock());37  child_thread_locked = true;38 39  while (keep_waiting)40    std::this_thread::sleep_for(std::chrono::milliseconds(10));41 42  child_thread_unlocked = true;43}44 45int main(int, char**) {46  {47    mux.lock();48    std::thread t        = support::make_test_thread(lock_thread);49    main_thread_unlocked = true;50    mux.unlock();51    t.join();52    assert(child_thread_unlocked);53  }54 55  {56    child_thread_unlocked = false;57    child_thread_locked   = false;58    keep_waiting          = true;59    std::thread t         = support::make_test_thread(try_lock_thread);60    while (!child_thread_locked)61      std::this_thread::sleep_for(std::chrono::milliseconds(10));62    assert(!mux.try_lock());63    keep_waiting = false;64    t.join();65    assert(child_thread_unlocked);66  }67 68  return 0;69}70