void thread_func(unsigned int id) { for (int i = 0; i < 10000; ++i) { printf("%d\n", s.down()); sched_yield(); printf("%d\n", s.up()); } }
TEST(EventCount, Simple) { // We're basically testing for no deadlock. static const size_t count = 300000; enum class Op { UP, DOWN }; std::vector<std::pair<Op, int>> ops; std::mt19937 rnd(randomNumberSeed()); randomPartition(rnd, Op::UP, count, ops); size_t uppers = ops.size(); randomPartition(rnd, Op::DOWN, count, ops); size_t downers = ops.size() - uppers; VLOG(1) << "Using " << ops.size() << " threads: uppers=" << uppers << " downers=" << downers << " sem_count=" << count; std::shuffle(ops.begin(), ops.end(), std::mt19937(std::random_device()())); std::vector<std::thread> threads; threads.reserve(ops.size()); Semaphore sem; for (auto& op : ops) { int n = op.second; if (op.first == Op::UP) { auto fn = [&sem, n] () mutable { while (n--) { sem.up(); } }; threads.push_back(std::thread(fn)); } else { auto fn = [&sem, n] () mutable { while (n--) { sem.down(); } }; threads.push_back(std::thread(fn)); } } for (auto& thread : threads) { thread.join(); } EXPECT_EQ(0, sem.value()); }