Skip to content

Instantly share code, notes, and snippets.

@Fohlen
Created February 2, 2019 22:14
Show Gist options
  • Save Fohlen/bf708bb8ce8d57110d82f60049129f1b to your computer and use it in GitHub Desktop.
Save Fohlen/bf708bb8ce8d57110d82f60049129f1b to your computer and use it in GitHub Desktop.
Thread control
#include <thread>
#include <iostream>
#include <chrono>
#include <future>
void threadFunction(std::shared_future<void> futureObj)
{
std::cout << "Thread Start" << std::endl;
while (futureObj.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout)
{
std::cout << "Doing Some Work" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
std::cout << "Thread End" << std::endl;
}
int main()
{
// Create a std::promise object
std::promise<void> exitSignal;
//Fetch std::future object associated with promise
std::shared_future<void> futureObj = exitSignal.get_future();
// Starting Thread & move the future object in lambda function by reference
std::thread th(&threadFunction, futureObj);
//Wait for thread to join
th.detach();
// Starting a second thread
std::thread th2(&threadFunction, futureObj);
th2.detach();
//Wait for 10 sec
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "Asking Thread to Stop" << std::endl;
//Set the value in promise
exitSignal.set_value();
std::cout << "Exiting Main Function" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment