From 6199cba9987e4c57481b053e9764bbaaafe3de65 Mon Sep 17 00:00:00 2001 From: krad Date: Thu, 25 Jun 2015 13:32:32 -0700 Subject: [PATCH] Fix race in unit test. Summary: Avoid falling victim to race condition. Test Plan: Run the unit test Reviewers: sdong igor CC: leveldb@ Task ID: #7312624 Blame Rev: --- db/db_test.cc | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/db/db_test.cc b/db/db_test.cc index f09578bb8..c38c709a6 100644 --- a/db/db_test.cc +++ b/db/db_test.cc @@ -72,21 +72,39 @@ static std::string RandomString(Random* rnd, int len) { namespace anon { class AtomicCounter { private: + Env* env_; port::Mutex mu_; + port::CondVar cond_count_; int count_; public: - AtomicCounter() : count_(0) { } + AtomicCounter(Env* env = NULL) : env_(env), cond_count_(&mu_), count_(0) {} void Increment() { MutexLock l(&mu_); count_++; + cond_count_.SignalAll(); } int Read() { MutexLock l(&mu_); return count_; } + bool WaitFor(int count) { + MutexLock l(&mu_); + + uint64_t start = env_->NowMicros(); + while (count_ < count) { + uint64_t now = env_->NowMicros(); + cond_count_.TimedWait(now + /*1s*/ 1 * 000 * 000); + if (env_->NowMicros() - start > /*1s*/ 1 * 000 * 000) { + return false; + } + } + + return true; + } void Reset() { MutexLock l(&mu_); count_ = 0; + cond_count_.SignalAll(); } }; @@ -159,7 +177,11 @@ class SpecialEnv : public EnvWrapper { bool no_sleep_; explicit SpecialEnv(Env* base) - : EnvWrapper(base), rnd_(301), addon_time_(0), no_sleep_(false) { + : EnvWrapper(base), + rnd_(301), + sleep_counter_(this), + addon_time_(0), + no_sleep_(false) { delay_sstable_sync_.store(false, std::memory_order_release); drop_writes_.store(false, std::memory_order_release); no_space_.store(false, std::memory_order_release); @@ -7553,7 +7575,7 @@ TEST_F(DBTest, DropWrites) { ASSERT_LT(CountFiles(), num_files + 3); // Check that compaction attempts slept after errors - ASSERT_GE(env_->sleep_counter_.Read(), 5); + ASSERT_TRUE(env_->sleep_counter_.WaitFor(5)); } while (ChangeCompactOptions()); }