2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/SpinLock.h>
19 #include <folly/Random.h>
23 #include <folly/portability/Asm.h>
24 #include <folly/portability/GTest.h>
26 using folly::SpinLockGuardImpl;
30 template <typename LOCK>
36 memset(ar, 0, sizeof ar);
40 template <typename LOCK>
41 void spinlockTestThread(LockedVal<LOCK>* v) {
43 auto rng = folly::ThreadLocalPRNG();
44 for (int i = 0; i < max; i++) {
45 folly::asm_volatile_pause();
46 SpinLockGuardImpl<LOCK> g(v->lock);
49 for (size_t j = 1; j < sizeof v->ar / sizeof j; ++j) {
50 EXPECT_EQ(first, v->ar[j]);
53 int byte = folly::Random::rand32(rng);
54 memset(v->ar, char(byte), sizeof v->ar);
58 template <typename LOCK>
67 template <typename LOCK>
68 void trylockTestThread(TryLockState<LOCK>* state, size_t count) {
70 folly::asm_volatile_pause();
71 bool ret = state->lock2.try_lock();
72 SpinLockGuardImpl<LOCK> g(state->lock1);
73 if (state->obtained >= count) {
75 state->lock2.unlock();
83 EXPECT_NE(state->locked, ret);
87 // Release lock1 and wait until at least one other thread fails to
88 // obtain the lock2 before continuing.
89 auto oldFailed = state->failed;
90 while (state->failed == oldFailed && state->obtained < count) {
91 state->lock1.unlock();
92 folly::asm_volatile_pause();
96 state->locked = false;
97 state->lock2.unlock();
104 template <typename LOCK>
105 void correctnessTest() {
106 int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2;
107 std::vector<std::thread> threads;
109 for (int i = 0; i < nthrs; ++i) {
110 threads.push_back(std::thread(spinlockTestThread<LOCK>, &v));
112 for (auto& t : threads) {
117 template <typename LOCK>
119 int nthrs = sysconf(_SC_NPROCESSORS_ONLN) + 4;
120 std::vector<std::thread> threads;
121 TryLockState<LOCK> state;
123 for (int i = 0; i < nthrs; ++i) {
124 threads.push_back(std::thread(trylockTestThread<LOCK>, &state, count));
126 for (auto& t : threads) {
130 EXPECT_EQ(count, state.obtained);
131 // Each time the code obtains lock2 it waits for another thread to fail
132 // to acquire it. The only time this might not happen is on the very last
133 // loop when no other threads are left.
134 EXPECT_GE(state.failed + 1, state.obtained);
137 } // unnamed namespace
139 TEST(SpinLock, Correctness) {
140 correctnessTest<folly::SpinLock>();
142 TEST(SpinLock, TryLock) {
143 trylockTest<folly::SpinLock>();