]> git.proxmox.com Git - ceph.git/blob - ceph/src/test/common/test_mutex_debug.cc
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / test / common / test_mutex_debug.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 &smarttab
3 /*
4 * Ceph - scalable distributed file system
5 *
6 * Copyright (C) 2011 New Dream Network
7 *
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public
10 * License version 2, as published by the Free Software
11 * Foundation. See file COPYING.
12 *
13 */
14
15 #include <future>
16 #include <mutex>
17 #include <thread>
18
19 #include "common/mutex_debug.h"
20
21 #include "gtest/gtest.h"
22
23
24 template<typename Mutex>
25 static bool test_try_lock(Mutex* m) {
26 if (!m->try_lock())
27 return false;
28 m->unlock();
29 return true;
30 }
31
32 template<typename Mutex>
33 static void test_lock() {
34 Mutex m;
35 auto ttl = &test_try_lock<Mutex>;
36
37 m.lock();
38 ASSERT_TRUE(m.is_locked());
39 auto f1 = std::async(std::launch::async, ttl, &m);
40 ASSERT_FALSE(f1.get());
41
42 ASSERT_TRUE(m.is_locked());
43 ASSERT_TRUE(!!m);
44
45 m.unlock();
46 ASSERT_FALSE(m.is_locked());
47 ASSERT_FALSE(!!m);
48
49 auto f3 = std::async(std::launch::async, ttl, &m);
50 ASSERT_TRUE(f3.get());
51
52 ASSERT_FALSE(m.is_locked());
53 ASSERT_FALSE(!!m);
54 }
55
56 TEST(MutexDebug, Lock) {
57 test_lock<ceph::mutex_debug>();
58 }
59
60 TEST(MutexDebug, NotRecursive) {
61 ceph::mutex_debug m;
62 auto ttl = &test_try_lock<mutex_debug>;
63
64 ASSERT_NO_THROW(m.lock());
65 ASSERT_TRUE(m.is_locked());
66 ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get());
67
68 ASSERT_THROW(m.lock(), std::system_error);
69 ASSERT_TRUE(m.is_locked());
70 ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get());
71
72 ASSERT_NO_THROW(m.unlock());
73 ASSERT_FALSE(m.is_locked());
74 ASSERT_TRUE(std::async(std::launch::async, ttl, &m).get());
75 }
76
77 TEST(MutexRecursiveDebug, Lock) {
78 test_lock<ceph::mutex_recursive_debug>();
79 }
80
81
82 TEST(MutexRecursiveDebug, Recursive) {
83 ceph::mutex_recursive_debug m;
84 auto ttl = &test_try_lock<mutex_recursive_debug>;
85
86 ASSERT_NO_THROW(m.lock());
87 ASSERT_TRUE(m.is_locked());
88 ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get());
89
90 ASSERT_NO_THROW(m.lock());
91 ASSERT_TRUE(m.is_locked());
92 ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get());
93
94 ASSERT_NO_THROW(m.unlock());
95 ASSERT_TRUE(m.is_locked());
96 ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get());
97
98 ASSERT_NO_THROW(m.unlock());
99 ASSERT_FALSE(m.is_locked());
100 ASSERT_TRUE(std::async(std::launch::async, ttl, &m).get());
101 }