2 * Copyright 2015 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/experimental/EventCount.h>
24 #include <glog/logging.h>
25 #include <gtest/gtest.h>
27 #include <folly/Random.h>
29 using namespace folly;
35 explicit Semaphore(int v=0) : value_(v) { }
38 ec_.await([this] { return tryDown(); });
52 for (int v = value_; v != 0;) {
53 if (value_.compare_exchange_weak(v, v-1)) {
60 std::atomic<int> value_;
64 template <class T, class Random>
65 void randomPartition(Random& random, T key, int n,
66 std::vector<std::pair<T, int>>& out) {
68 int m = std::min(n, 1000);
69 std::uniform_int_distribution<uint32_t> u(1, m);
71 out.emplace_back(key, cut);
78 TEST(EventCount, Simple) {
79 // We're basically testing for no deadlock.
80 static const size_t count = 300000;
86 std::vector<std::pair<Op, int>> ops;
87 std::mt19937 rnd(randomNumberSeed());
88 randomPartition(rnd, Op::UP, count, ops);
89 size_t uppers = ops.size();
90 randomPartition(rnd, Op::DOWN, count, ops);
91 size_t downers = ops.size() - uppers;
92 VLOG(1) << "Using " << ops.size() << " threads: uppers=" << uppers
93 << " downers=" << downers << " sem_count=" << count;
95 std::random_shuffle(ops.begin(), ops.end());
97 std::vector<std::thread> threads;
98 threads.reserve(ops.size());
101 for (auto& op : ops) {
103 if (op.first == Op::UP) {
104 auto fn = [&sem, n] () mutable {
109 threads.push_back(std::thread(fn));
111 auto fn = [&sem, n] () mutable {
116 threads.push_back(std::thread(fn));
120 for (auto& thread : threads) {
124 EXPECT_EQ(0, sem.value());