From 2fd43019d3373ef420f56c431e89d600414748ad Mon Sep 17 00:00:00 2001 From: Mislav Bradac Date: Mon, 9 Oct 2017 14:44:11 +0200 Subject: [PATCH] Change scheduler to first wait then execute Reviewers: dgleich Reviewed By: dgleich Subscribers: pullbot Differential Revision: https://phabricator.memgraph.io/D884 --- src/utils/scheduler.hpp | 13 ++++++++++--- tests/unit/scheduler.cpp | 22 ++++++++++++---------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/utils/scheduler.hpp b/src/utils/scheduler.hpp index 4004dfc6a..371dbaa33 100644 --- a/src/utils/scheduler.hpp +++ b/src/utils/scheduler.hpp @@ -32,9 +32,13 @@ class Scheduler { thread_ = std::thread([this, pause, f]() { auto start_time = std::chrono::system_clock::now(); - while (is_working_) { - f(); - + while (true) { + // First wait then execute the function. We do that in that order + // because most of the schedulers are started at the beginning of the + // program and there is probably no work to do in scheduled function at + // the start of the program. Since Server will log some messages on + // the program start we let him log first and we make sure by first + // waiting that funcion f will not log before it. std::unique_lock lk(mutex_); auto now = std::chrono::system_clock::now(); start_time += pause; @@ -45,6 +49,9 @@ class Scheduler { } else { start_time = now; } + + if (!is_working_) break; + f(); } }); } diff --git a/tests/unit/scheduler.cpp b/tests/unit/scheduler.cpp index bc4a4330b..2fde2fc8d 100644 --- a/tests/unit/scheduler.cpp +++ b/tests/unit/scheduler.cpp @@ -10,20 +10,22 @@ * value. */ TEST(Scheduler, TestFunctionExecuting) { - std::atomic x{0}, y{0}; - std::function func{[&x, &y]() { - EXPECT_EQ(y.load(), x.load()); - x++; - }}; + std::atomic x{0}; + std::function func{[&x]() { ++x; }}; Scheduler scheduler; scheduler.Run(std::chrono::seconds(1), func); - std::this_thread::sleep_for(std::chrono::milliseconds(980)); - y++; - EXPECT_EQ(x.load(), y.load()); + EXPECT_EQ(x, 0); + std::this_thread::sleep_for(std::chrono::milliseconds(900)); + EXPECT_EQ(x, 0); + + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + EXPECT_EQ(x, 1); + + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + EXPECT_EQ(x, 3); std::this_thread::sleep_for(std::chrono::milliseconds(100)); scheduler.Stop(); - y++; - EXPECT_EQ(x.load(), y.load()); + EXPECT_EQ(x, 3); }