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-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// UNSUPPORTED: no-threads
10// UNSUPPORTED: c++03, c++11
11
12// <shared_mutex>
13
14// class shared_timed_mutex;
15
16#include <shared_mutex>
17
18#include <atomic>
19#include <chrono>
20#include <thread>
21#include <cstdlib>
22#include <cassert>
23
24#include "make_test_thread.h"
25#include "test_macros.h"
26
27std::shared_timed_mutex m;
28
29const int total_readers = 2;
30std::atomic<int> readers_started(0);
31std::atomic<int> readers_finished(0);
32
33// Wait for the readers to start then try and acquire the write lock.
34void writer_one() {
35 while (readers_started != total_readers) {}
36 bool b = m.try_lock_for(rtime: std::chrono::milliseconds(500));
37 assert(b == false);
38}
39
40void blocked_reader() {
41 ++readers_started;
42 // Wait until writer_one is waiting for the write lock.
43 while (m.try_lock_shared()) {
44 m.unlock_shared();
45 }
46 // Attempt to get the read lock. writer_one should be blocking us because
47 // writer_one is blocked by main.
48 m.lock_shared();
49 ++readers_finished;
50 m.unlock_shared();
51}
52
53int main(int, char**)
54{
55 typedef std::chrono::steady_clock Clock;
56
57 m.lock_shared();
58 std::thread t1 = support::make_test_thread(writer_one);
59 // create some readers
60 std::thread t2 = support::make_test_thread(blocked_reader);
61 std::thread t3 = support::make_test_thread(blocked_reader);
62 // Kill the test after 10 seconds if it hasn't completed.
63 auto end_point = Clock::now() + std::chrono::seconds(10);
64 while (readers_finished != total_readers && Clock::now() < end_point) {
65 std::this_thread::sleep_for(rtime: std::chrono::seconds(1));
66 }
67 assert(readers_finished == total_readers);
68 m.unlock_shared();
69 t1.join();
70 t2.join();
71 t3.join();
72
73 return 0;
74}
75

source code of libcxx/test/std/thread/thread.mutex/thread.mutex.requirements/thread.sharedtimedmutex.requirements/thread.sharedtimedmutex.class/try_lock_until_deadlock_bug.pass.cpp