I wanted to write a quick and dirty code... but I didn't want to make it lousy in execution. Had simple requirement: Run a piece of code in a separate thread every 6 seconds but have ability to terminate (almost) immediately. Like any other lousy programmer, I didn't want to implement a timer (which is lengthy process in C++). So I stumbled upon a solution which uses std::future to terminate the sleep immediately and doesn't execute anything once the future times out. Even if I was using while loop instead of do..while, it would have come out of the scope immediately. I am publishing it here as my example is more clear and that "Bad bad code." is present in that solution. Happy programming!
to compile: > g++ -pthread test.cpp
#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
using namespace std;
void threadFunction(std::future<void> future){
std::cout << "Starting the thread" << std::endl;
do {
std::cout << "Executing the thread....." << std::endl;
//std::this_thread::sleep_for(std::chrono::milliseconds(6000)); //bad bad code
} while (future.wait_for(std::chrono::milliseconds(6000)) == std::future_status::timeout);
std::cout << "Thread Terminated" << std::endl;
}
main(){
std::promise<void> signal_exit; //create promise object
std::future<void> future = signal_exit.get_future();//create future objects
std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future
std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds
std::cout << "Threads will be stopped soon...." << std::endl;
signal_exit.set_value(); //set value into promise
my_thread.join(); //join the thread with the main thread
std::cout << "Doing task in main function" << std::endl;
}