-
Notifications
You must be signed in to change notification settings - Fork 23
Open
Description
Here's the constructor:
Timer(const Duration interval, const Callback& callback) {
auto value = duration_cast<milliseconds>(interval);
sync_cout << "Timer: Starting with interval of " << value << std::endl;
t = std::jthread([&](std::stop_token stop_token) {
while (!stop_token.stop_requested()) {
sync_cout << "Timer: Running callback " << val.load() << " ...\n";
val++;
callback();
sync_cout << "Timer: Sleeping...\n";
std::this_thread::sleep_for(interval);
}
sync_cout << "Timer: Exit\n";
});
}
In there the lambda for the thread captures everything by reference, which means that interval used below is long gone when the thread runs and the timer does not sleeps at all. Here's the correct code (capturing value by value:
Timer(const Duration interval, const Callback& callback) {
auto value = duration_cast<milliseconds>(interval);
sync_cout << "Timer: Starting with interval of " << value << std::endl;
t = std::jthread([&, value](std::stop_token stop_token) {
while (!stop_token.stop_requested()) {
sync_cout << "Timer: Running callback " << val.load() << " ...\n";
val++;
callback();
sync_cout << "Timer: Sleeping...\n";
std::this_thread::sleep_for(value);
}
sync_cout << "Timer: Exit\n";
});
}
Metadata
Metadata
Assignees
Labels
No labels