| 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 |
// ALLOW_RETRIES: 2 |
| 12 |
|
| 13 |
// <shared_mutex> |
| 14 |
|
| 15 |
// template <class Mutex> class shared_lock; |
| 16 |
|
| 17 |
// shared_lock(mutex_type& m, try_to_lock_t); |
| 18 |
|
| 19 |
#include <cassert> |
| 20 |
#include <chrono> |
| 21 |
#include <cstdlib> |
| 22 |
#include <mutex> |
| 23 |
#include <shared_mutex> |
| 24 |
#include <thread> |
| 25 |
#include <vector> |
| 26 |
|
| 27 |
#include "make_test_thread.h" |
| 28 |
#include "test_macros.h" |
| 29 |
|
| 30 |
std::shared_timed_mutex m; |
| 31 |
|
| 32 |
typedef std::chrono::system_clock Clock; |
| 33 |
typedef Clock::time_point time_point; |
| 34 |
typedef Clock::duration duration; |
| 35 |
typedef std::chrono::milliseconds ms; |
| 36 |
typedef std::chrono::nanoseconds ns; |
| 37 |
|
| 38 |
|
| 39 |
// Thread sanitizer causes more overhead and will sometimes cause this test |
| 40 |
// to fail. To prevent this we give Thread sanitizer more time to complete the |
| 41 |
// test. |
| 42 |
#if !defined(TEST_IS_EXECUTED_IN_A_SLOW_ENVIRONMENT) |
| 43 |
ms Tolerance = ms(200); |
| 44 |
#else |
| 45 |
ms Tolerance = ms(200 * 5); |
| 46 |
#endif |
| 47 |
|
| 48 |
void f() |
| 49 |
{ |
| 50 |
time_point t0 = Clock::now(); |
| 51 |
{ |
| 52 |
std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); |
| 53 |
assert(lk.owns_lock() == false); |
| 54 |
} |
| 55 |
{ |
| 56 |
std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); |
| 57 |
assert(lk.owns_lock() == false); |
| 58 |
} |
| 59 |
{ |
| 60 |
std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); |
| 61 |
assert(lk.owns_lock() == false); |
| 62 |
} |
| 63 |
while (true) |
| 64 |
{ |
| 65 |
std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); |
| 66 |
if (lk.owns_lock()) |
| 67 |
break; |
| 68 |
std::this_thread::yield(); |
| 69 |
} |
| 70 |
time_point t1 = Clock::now(); |
| 71 |
ns d = t1 - t0 - ms(250); |
| 72 |
assert(d < Tolerance); // within tolerance |
| 73 |
} |
| 74 |
|
| 75 |
int main(int, char**) |
| 76 |
{ |
| 77 |
m.lock(); |
| 78 |
std::vector<std::thread> v; |
| 79 |
for (int i = 0; i < 5; ++i) |
| 80 |
v.push_back(support::make_test_thread(f)); |
| 81 |
std::this_thread::sleep_for(ms(250)); |
| 82 |
m.unlock(); |
| 83 |
for (auto& t : v) |
| 84 |
t.join(); |
| 85 |
|
| 86 |
return 0; |
| 87 |
} |