Repeatedly execute a task in C++
This post will discuss how to repeatedly execute a task in C++.
In programming, threads are often used for the concurrent execution of multiple functions. In C++, the std::thread class offers the facility for threads to schedule tasks for repeated execution. Consider the following code which implements a simple timer. The code uses std::this_thread::sleep_until which blocks the execution of the current thread until the specified duration has been reached.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <chrono> #include <thread> #include <functional> void run(std::function<void(void)> f, int duration) { std::thread([f, duration]() { while (true) { f(); auto ms = std::chrono::steady_clock::now() + std::chrono::milliseconds(duration); std::this_thread::sleep_until(ms); } }).detach(); } void foo() { std::cout << "Running.." << std::endl; } int main() { run(foo, 1000); while (true); } |
Note that the above solution repeatedly executes the specified function until the program is terminated. Here’s an alternative version using the std::this_thread::sleep_for which blocks the execution of the current thread for the specified duration.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <chrono> #include <thread> #include <functional> void run(std::function<void(void)> f, int duration) { std::thread([f, duration]() { while (true) { f(); std::this_thread::sleep_for(std::chrono::milliseconds(duration)); } }).detach(); } void foo() { std::cout << "Running.." << std::endl; } int main() { run(foo, 1000); while (true); } |
That’s all about repeatedly executing a task in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)