Create and terminate threads from main thread
Jul 9, 2014 at 10:11am UTC
I have a non static class that does some calculation upon receiving data updates. However for some kind of update it wishes to asynchronously wait a while before calculating. Nonetheless, for another kind of updates it will stop the waiting and update immediately. I've looked at std::thread and the Window's API CreateThread to do this. Unfortunately, I can't find a way to kill a std::thread, and CreateThread requires the calculation function to be static which is impossible.
Can anyone help to suggest what I can do about this?
pseudo code below:
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
class SignalReceiver {
private :
bool thread_created;
public :
void Calculate() {
// do something here based on its internal state. Cannot be static
}
void WaitAndCalculate() {
Sleep(5000); // wait 5 sec
Calculate();
thread_created = false ;
}
void ReceiveSignal(string signal) {
if (signal == "now" ) {
if (thread_created) {
KillThread (waitThread);
}
Calculate();
} else if (signal == "wait" ) {
if (!thread_created) {
waitThread = CreateThread (WaitAndCalculate);
thread_created = true ;
}
}
}
}
ReceiveSignal is called asynchronously. Calculate and WaitAndCalculate cannot be static as it needs to access the class internal variables
Last edited on Jul 9, 2014 at 10:12am UTC
Jul 9, 2014 at 11:37am UTC
Something like this, perhaps:
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
#include <string>
#include <atomic>
struct signal_recvr
{
void recv_signal( std::string signal )
{
++i ;
if ( signal == "now" ) wait_and_calculate() ;
else std::thread( &signal_recvr::calculate, this ).detach() ;
}
~signal_recvr()
{
while ( thread_cnt > 0 ) std::this_thread::sleep_for( std::chrono::milliseconds(10) ) ;
std::lock_guard<std::mutex> guard(result_lock) ;
for ( int v : result ) std::cout << v << ' ' ; std::cout << '\n' ;
}
private :
void calculate()
{
++thread_cnt ;
std::lock_guard<std::mutex> guard(result_lock) ;
result.push_back( 100 - i ) ;
--thread_cnt ;
}
void wait_and_calculate()
{
std::this_thread::sleep_for( std::chrono::seconds(1) ) ;
std::lock_guard<std::mutex> guard(result_lock) ;
result.push_back(i) ;
}
std::atomic<int > i {0} ;
std::atomic<int > thread_cnt {0} ;
std::vector<int > result ;
std::mutex result_lock ;
};
int main()
{
signal_recvr recvr ;
for ( int i = 0 ; i < 10 ; ++i )
{
recvr.recv_signal( i%2 ? "now" : "later" ) ;
std::this_thread::sleep_for( std::chrono::milliseconds(1) ) ;
}
}
http://coliru.stacked-crooked.com/a/4a83fbb6dd27dde3
Topic archived. No new replies allowed.