memcheck/tests/sh-mem-random.c: Set huge_addr to 240GB
[valgrind.git] / drd / tests / shared_timed_mutex.cpp
blobdfd97a4b812fc7a2ff92d69083a9b6845f5f7911
1 #include <thread>
2 #include <iostream>
3 #include <chrono>
4 #include <shared_mutex>
5 #include <mutex>
6 #include <cassert>
7 #include <condition_variable>
9 std::shared_timed_mutex test_mutex;
10 std::mutex cv_mutex;
11 std::condition_variable cv;
12 int global;
13 bool reads_done = false;
15 void f()
17 auto now=std::chrono::steady_clock::now();
18 auto then = now + std::chrono::seconds(3);
19 int i;
20 for (i = 0; i < 3 && std::chrono::steady_clock::now() < then; ++i)
22 if (test_mutex.try_lock_until(then))
24 --global;
25 test_mutex.unlock();
26 break;
30 if (i == 3)
32 std::cerr << "Lock failed\n";
36 void g()
38 auto now=std::chrono::steady_clock::now();
39 auto then = now + std::chrono::seconds(2);
40 int i;
41 for (i = 0; i < 3 && std::chrono::steady_clock::now() < then; ++i)
43 if (test_mutex.try_lock_shared_until(then))
45 test_mutex.unlock_shared();
46 break;
49 if (i == 3)
51 std::cerr << "Lock shared failed\n";
53 std::unique_lock<std::mutex> lock(cv_mutex);
54 reads_done = true;
55 cv.notify_all();
58 int main()
60 global = 1;
61 test_mutex.lock_shared();
62 std::thread t1(f);
63 std::thread t2(g);
65 std::unique_lock<std::mutex> lock(cv_mutex);
66 while (!reads_done)
68 cv.wait(lock);
71 test_mutex.unlock_shared();
72 t1.join();
73 t2.join();
74 assert(global == 0);