相关文章推荐
耍酷的人字拖  ·  .Net ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

Make sure you call join() on the thread before the assignment. Otherwise the old thread will be considered active and the assignment operator will throw an exception. – Alexandru C. Dec 21, 2015 at 13:44 Warning: the code doesn't use old thread - it just create new one and assign it to the old object. – Mariusz Jaskółka Jan 3, 2017 at 19:32

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.