2 * Copyright 2014 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.
16 #include <folly/SpinLock.h>
18 #include <gtest/gtest.h>
21 using folly::SpinLock;
22 using folly::SpinLockGuard;
31 memset(ar, 0, sizeof ar);
38 unsigned int seed = (uintptr_t)pthread_self();
39 for (int i = 0; i < max; i++) {
41 SpinLockGuard g(v.lock);
44 for (size_t i = 1; i < sizeof v.ar / sizeof i; ++i) {
45 EXPECT_EQ(first, v.ar[i]);
48 int byte = rand_r(&seed);
49 memset(v.ar, char(byte), sizeof v.ar);
60 TryLockState tryState;
66 SpinLockGuard g(tryState.lock1);
67 if (tryState.obtained >= max) {
71 bool ret = tryState.lock2.trylock();
72 EXPECT_NE(tryState.locked, ret);
77 tryState.locked = true;
79 // Release lock1 and let other threads try to obtain lock2
80 tryState.lock1.unlock();
82 tryState.lock1.lock();
84 tryState.locked = false;
85 tryState.lock2.unlock();
92 } // unnamed namespace
94 TEST(SpinLock, Correctness) {
95 int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2;
96 std::vector<std::thread> threads;
97 for (int i = 0; i < nthrs; ++i) {
98 threads.push_back(std::thread(splock_test));
100 for (auto& t : threads) {
105 TEST(SpinLock, TryLock) {
106 int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2;
107 std::vector<std::thread> threads;
108 for (int i = 0; i < nthrs; ++i) {
109 threads.push_back(std::thread(trylock_test));
111 for (auto& t : threads) {
115 EXPECT_EQ(1000, tryState.obtained);
116 EXPECT_GT(tryState.failed, 0);
117 LOG(INFO) << "failed count: " << tryState.failed;