Marshall Clow | abadb45 | 2015-06-30 14:04:14 +0000 | [diff] [blame] | 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is dual licensed under the MIT and the University of Illinois Open |
| 6 | // Source Licenses. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // UNSUPPORTED: libcpp-has-no-threads |
| 11 | // UNSUPPORTED: c++03, c++98, c++11, c++14 |
| 12 | |
| 13 | // <shared_mutex> |
| 14 | |
| 15 | // class shared_mutex; |
| 16 | |
| 17 | // void lock_shared(); |
| 18 | |
| 19 | #include <shared_mutex> |
| 20 | #include <thread> |
| 21 | #include <vector> |
| 22 | #include <cstdlib> |
| 23 | #include <cassert> |
| 24 | |
| 25 | std::shared_mutex m; |
| 26 | |
| 27 | typedef std::chrono::system_clock Clock; |
| 28 | typedef Clock::time_point time_point; |
| 29 | typedef Clock::duration duration; |
| 30 | typedef std::chrono::milliseconds ms; |
| 31 | typedef std::chrono::nanoseconds ns; |
| 32 | |
| 33 | void f() |
| 34 | { |
| 35 | time_point t0 = Clock::now(); |
| 36 | m.lock_shared(); |
| 37 | time_point t1 = Clock::now(); |
| 38 | m.unlock_shared(); |
Dan Albert | 1d4a1ed | 2016-05-25 22:36:09 -0700 | [diff] [blame^] | 39 | ns d = t1 - t0 - ms(250); |
| 40 | assert(d < ms(50)); // within 50ms |
Marshall Clow | abadb45 | 2015-06-30 14:04:14 +0000 | [diff] [blame] | 41 | } |
| 42 | |
| 43 | void g() |
| 44 | { |
| 45 | time_point t0 = Clock::now(); |
| 46 | m.lock_shared(); |
| 47 | time_point t1 = Clock::now(); |
| 48 | m.unlock_shared(); |
| 49 | ns d = t1 - t0; |
Dan Albert | 1d4a1ed | 2016-05-25 22:36:09 -0700 | [diff] [blame^] | 50 | assert(d < ms(50)); // within 50ms |
Marshall Clow | abadb45 | 2015-06-30 14:04:14 +0000 | [diff] [blame] | 51 | } |
| 52 | |
| 53 | |
| 54 | int main() |
| 55 | { |
| 56 | m.lock(); |
| 57 | std::vector<std::thread> v; |
| 58 | for (int i = 0; i < 5; ++i) |
| 59 | v.push_back(std::thread(f)); |
Dan Albert | 1d4a1ed | 2016-05-25 22:36:09 -0700 | [diff] [blame^] | 60 | std::this_thread::sleep_for(ms(250)); |
Marshall Clow | abadb45 | 2015-06-30 14:04:14 +0000 | [diff] [blame] | 61 | m.unlock(); |
| 62 | for (auto& t : v) |
| 63 | t.join(); |
| 64 | m.lock_shared(); |
| 65 | for (auto& t : v) |
| 66 | t = std::thread(g); |
| 67 | std::thread q(f); |
Dan Albert | 1d4a1ed | 2016-05-25 22:36:09 -0700 | [diff] [blame^] | 68 | std::this_thread::sleep_for(ms(250)); |
Marshall Clow | abadb45 | 2015-06-30 14:04:14 +0000 | [diff] [blame] | 69 | m.unlock_shared(); |
| 70 | for (auto& t : v) |
| 71 | t.join(); |
| 72 | q.join(); |
| 73 | } |