I have this line of code in my main()
method of my C++ method:
std::thread foo (bar);
That works fine. However, I would like to run this same thread any time that I want to based on external input. How can I re-use this thread to run the thread again?
The reason I'm doing this is I have two functions that need to be ran at the same time: one that is blocking and takes an input, x, and outputs the data to the output at set intervals. The other one is blocking and produces an output, y, based on external input. This is basically what it should look like:
int shared_x = 0;
int producer_x = 0;
int consumer_x = 0;
std::thread producer (foo); //Modifies foo_x
std::thread consumer (bar); //Outputs based on foo2_x
while( ;; ) {
if(producer .join()) {
shared_x = producer_x;
//How should I restart the thread here?
}
if(consumer.join()) {
consumer_x = shared_x;
//Here too?
}
}
That seems to handle the whole thread safety issue and allow them both to safely operate at the same time with little time waiting. The only issue is I don't know how to restart the thread. How do I do this?
Reading through some documentation, I found this works:
myOldThread = thread(foobar);
I assume there's still quite a bit of performance overhead, but at least I can reuse the same variable. :/
An alternative approach would be to never let the thread die (have a loop with a 200ms delay that checks a mutex-protected boolean for when it should run again). Not super clean, but if performance matters, this is probably the best way to do this.
Boost::ThreadPool could also be a good option. By using that you can pick threads from pool to assign tasks.
How to create a thread pool using boost in C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With