olidev
olidev

Reputation: 20624

wait for other thread to proceed

In C++, I have this sample implementation:

#include <thread>
#include <iostream>

void doSomeWork( void )
{
    std::cout << "hello from thread..." << std::endl;
    while(true)
    {
       printf("Getting inside doSomeWork\n");
       sleep(1);
    }
}

int main( int argc, char *argv[] )
{
    std::thread t( doSomeWork );
    t.join();

    processing();

    return 0;
}

void processing()
{
   while(true)
   {
      printf("Getting inside processing\n");
      sleep(1);
   }
}

I have a problem that doSomeWork() keep doing things and it block processing(). I thought thread is asynchronous so that while it is sleeping, I can other things. My question here is how can I sleep in doSomeWork() and yield other threads, then resume doSomework()?

Upvotes: 1

Views: 319

Answers (2)

ixSci
ixSci

Reputation: 13698

replace t.join(); with t.detach();

Note however, detach means something like "I'm not interesting in this thread, so it may be terminated in any time" or "I will synchronize the thread by some sync mechanism". Basically it is used when you have some external(to the thread) sync mechanism so you don't want to use join. It is common to use join every time but use detach only when needed. In your particular case you have sync mechanism with forever loop, so it is absolutely fine to use detach but be aware about their differences.

Upvotes: 2

simonc
simonc

Reputation: 42165

The line

t.join();

pauses the calling thread until thread t completes (when doSomeWork()) returns.

Change your code to

std::thread t( doSomeWork );
processing();
t.join();

if you want processing() and doSomeWork() to run in parallel.

Upvotes: 6

Related Questions