]>
git.proxmox.com Git - ceph.git/blob - ceph/src/test/simple_spin.cc
4 #include "gtest/gtest.h"
6 #include "include/spinlock.h"
9 using ceph::spin_unlock
;
11 static std::atomic_flag lock
= ATOMIC_FLAG_INIT
;
12 static int64_t counter
= 0;
14 TEST(SimpleSpin
, Test0
)
16 std::atomic_flag lock0
= ATOMIC_FLAG_INIT
;
21 static void* mythread(void *v
)
23 for (int j
= 0; j
< 1000000; ++j
) {
31 TEST(SimpleSpin
, Test1
)
34 const auto n
= 2000000U;
39 ret
= pthread_create(&thread1
, NULL
, mythread
, NULL
);
41 ret
= pthread_create(&thread2
, NULL
, mythread
, NULL
);
43 ret
= pthread_join(thread1
, NULL
);
45 ret
= pthread_join(thread2
, NULL
);
47 ASSERT_EQ(n
, counter
);
49 // Should also work with pass-by-reference:
50 // (Note that we don't care about cross-threading here as-such.)
52 auto f
= async(std::launch::async
, []() {
53 for(int i
= 0; n
!= i
; ++i
) {
60 ASSERT_EQ(n
, counter
);
63 template <typename LockT
>
64 int64_t check_lock_unlock(const int64_t n
, int64_t& cntr
, LockT
& lock
)
66 auto do_lock_unlock
= [&]() -> int64_t {
78 auto fone
= async(std::launch::async
, do_lock_unlock
);
79 auto ftwo
= async(std::launch::async
, do_lock_unlock
);
80 auto fthree
= async(std::launch::async
, do_lock_unlock
);
82 auto one
= fone
.get();
83 auto two
= ftwo
.get();
84 auto three
= fthree
.get();
86 // Google test doesn't like us using its macros out of individual tests, so:
87 if(n
!= one
|| n
!= two
|| n
!= three
)
90 return one
+ two
+ three
;
93 TEST(SimpleSpin
, Test2
)
95 const auto n
= 2000000U;
102 ASSERT_EQ(0, counter
);
103 auto result
= check_lock_unlock(n
, counter
, l
);
104 ASSERT_NE(0, counter
);
105 ASSERT_EQ(counter
, result
);
109 // ceph::spinlock should work with std::lock_guard<>:
110 TEST(SimpleSpin
, spinlock_guard
)
112 const auto n
= 2000000U;
117 auto f
= async(std::launch::async
, [&sl
]() {
118 for(int i
= 0; n
!= i
; ++i
) {
119 std::lock_guard
<ceph::spinlock
> g(sl
);
124 auto g
= async(std::launch::async
, [&sl
]() {
125 for(int i
= 0; n
!= i
; ++i
) {
126 std::lock_guard
<ceph::spinlock
> g(sl
);
133 ASSERT_EQ(2*n
, counter
);