In C ++, how can I reuse the standard stream that has finished executing?

I have this line of code in my method of main()

my C ++ method:

std::thread foo (bar);

      

This works great. However, I would like to run this same thread anytime I want based on external input. How can I reuse this thread to restart the thread?

The reason I am doing this is because I have two functions that need to be run at the same time: one that blocks and accepts input, x, and outputs data to the output at set intervals. The other blocks and exits, y, based on the external input. Basically it should look like this:

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

      

It seems to tackle the whole thread safety issue and allow them to run safely at the same time at the same time with little latency. The only problem is I don't know how to restart the thread. How to do it?

+3


source to share


2 answers


After reading some documentation I found this to work:

myOldThread = thread(foobar);

      

I guess there is still quite a bit of overhead overhead, but at least I can reuse the same variable.: /




An alternative approach would be to never allow the thread to die (have a 200ms delay loop that checks the boolean protected by the mutex when it should start again). Not super clean, but if performance matters, this is probably the best way to do it.

+2


source


Boost :: ThreadPool might also be a good option. Using this, you can select threads from the pool for task assignment.



How can I create a thread pool using boost in C ++?

+1


source







All Articles