Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, how can I reuse a standard thread that has finished execution?

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?

like image 747
Anonymous Penguin Avatar asked Oct 17 '14 03:10

Anonymous Penguin


2 Answers

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.

like image 148
Anonymous Penguin Avatar answered Nov 08 '22 06:11

Anonymous Penguin


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++?

like image 41
ravi Avatar answered Nov 08 '22 05:11

ravi