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.
17 #include <folly/Baton.h>
18 #include <folly/test/DeterministicSchedule.h>
20 #include <semaphore.h>
21 #include <gflags/gflags.h>
22 #include <gtest/gtest.h>
23 #include <folly/Benchmark.h>
25 using namespace folly;
26 using namespace folly::test;
28 typedef DeterministicSchedule DSched;
36 template <template<typename> class Atom>
37 void run_pingpong_test(int numRounds) {
38 Baton<Atom> batons[17];
39 Baton<Atom>& a = batons[0];
40 Baton<Atom>& b = batons[16]; // to get it on a different cache line
41 auto thr = DSched::thread([&]{
42 for (int i = 0; i < numRounds; ++i) {
48 for (int i = 0; i < numRounds; ++i) {
56 TEST(Baton, pingpong) {
57 DSched sched(DSched::uniform(0));
59 run_pingpong_test<DeterministicAtomic>(1000);
62 BENCHMARK(baton_pingpong, iters) {
63 run_pingpong_test<std::atomic>(iters);
66 BENCHMARK(posix_sem_pingpong, iters) {
69 sem_t* b = sems + 2; // to get it on a different cache line
73 auto thr = std::thread([=]{
74 for (int i = 0; i < iters; ++i) {
79 for (int i = 0; i < iters; ++i) {
86 // I am omitting a benchmark result snapshot because these microbenchmarks
87 // mainly illustrate that PreBlockAttempts is very effective for rapid
88 // handoffs. The performance of Baton and sem_t is essentially identical
89 // to the required futex calls for the blocking case
91 int main(int argc, char** argv) {
92 testing::InitGoogleTest(&argc, argv);
93 gflags::ParseCommandLineFlags(&argc, &argv, true);
95 auto rv = RUN_ALL_TESTS();
96 if (!rv && FLAGS_benchmark) {
97 folly::runBenchmarks();