Change scheduler to first wait then execute
Reviewers: dgleich Reviewed By: dgleich Subscribers: pullbot Differential Revision: https://phabricator.memgraph.io/D884
This commit is contained in:
parent
cffa5f6c96
commit
2fd43019d3
@ -32,9 +32,13 @@ class Scheduler {
|
|||||||
thread_ = std::thread([this, pause, f]() {
|
thread_ = std::thread([this, pause, f]() {
|
||||||
auto start_time = std::chrono::system_clock::now();
|
auto start_time = std::chrono::system_clock::now();
|
||||||
|
|
||||||
while (is_working_) {
|
while (true) {
|
||||||
f();
|
// 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<std::mutex> lk(mutex_);
|
std::unique_lock<std::mutex> lk(mutex_);
|
||||||
auto now = std::chrono::system_clock::now();
|
auto now = std::chrono::system_clock::now();
|
||||||
start_time += pause;
|
start_time += pause;
|
||||||
@ -45,6 +49,9 @@ class Scheduler {
|
|||||||
} else {
|
} else {
|
||||||
start_time = now;
|
start_time = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!is_working_) break;
|
||||||
|
f();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -10,20 +10,22 @@
|
|||||||
* value.
|
* value.
|
||||||
*/
|
*/
|
||||||
TEST(Scheduler, TestFunctionExecuting) {
|
TEST(Scheduler, TestFunctionExecuting) {
|
||||||
std::atomic<int> x{0}, y{0};
|
std::atomic<int> x{0};
|
||||||
std::function<void()> func{[&x, &y]() {
|
std::function<void()> func{[&x]() { ++x; }};
|
||||||
EXPECT_EQ(y.load(), x.load());
|
|
||||||
x++;
|
|
||||||
}};
|
|
||||||
Scheduler scheduler;
|
Scheduler scheduler;
|
||||||
scheduler.Run(std::chrono::seconds(1), func);
|
scheduler.Run(std::chrono::seconds(1), func);
|
||||||
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(980));
|
EXPECT_EQ(x, 0);
|
||||||
y++;
|
std::this_thread::sleep_for(std::chrono::milliseconds(900));
|
||||||
EXPECT_EQ(x.load(), y.load());
|
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));
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
scheduler.Stop();
|
scheduler.Stop();
|
||||||
y++;
|
EXPECT_EQ(x, 3);
|
||||||
EXPECT_EQ(x.load(), y.load());
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user