1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: no-threads
// <mutex>
// Make sure std::unique_lock works with std::mutex as expected.
#include <atomic>
#include <cassert>
#include <mutex>
#include "make_test_thread.h"
std::atomic<bool> keep_waiting;
std::atomic<bool> child_thread_locked;
std::mutex mux;
bool main_thread_unlocked = false;
bool child_thread_unlocked = false;
void lock_thread() {
std::unique_lock<std::mutex> lock(mux);
assert(main_thread_unlocked);
main_thread_unlocked = false;
child_thread_unlocked = true;
}
void try_lock_thread() {
std::unique_lock<std::mutex> lock(mux, std::try_to_lock_t());
assert(lock.owns_lock());
child_thread_locked = true;
while (keep_waiting)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
child_thread_unlocked = true;
}
int main(int, char**) {
{
mux.lock();
std::thread t = support::make_test_thread(lock_thread);
main_thread_unlocked = true;
mux.unlock();
t.join();
assert(child_thread_unlocked);
}
{
child_thread_unlocked = false;
child_thread_locked = false;
keep_waiting = true;
std::thread t = support::make_test_thread(try_lock_thread);
while (!child_thread_locked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
assert(!mux.try_lock());
keep_waiting = false;
t.join();
assert(child_thread_unlocked);
}
return 0;
}
|