0

I want to create a multi-threaded C++ program using boost. What I want to do, is to call a function Alpha, which sleeps, and prints out some messages. Whilst that function is being processed, i.e. sleeping, then I want my main program to continue. So, I want Alpha to run in the background, without interrupting the main function.

Here is my code:

void Alpha()
{
    std::cout << "Starting sleep." << std::endl;
    sleep(5);
    std::cout << "Sleep over." << std::endl;
}   

int main()
{
    std::cout << "A" << std::endl;
    boost::thread threadAlpha(Alpha);
    threadAlpha.join();
    std::cout << "B" << std::endl;
}

The output I get is:

A
Starting sleep.
Sleep over.
B

However, I want the thread to run in the background, such that it does not cause the main loop to wait. Therefore, I was expecting the output to be:

A
Starting sleep.
B
Sleep over.

Or possibly:

A
B
Starting sleep.
Sleep over.

Why is this not behaving as I would expect?

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • Boost multi-threading made it to the Standard quite a while ago (C++11). It's now called `std::thread`. – MSalters Mar 12 '15 at 14:21

2 Answers2

0

join does wait for the thread to finish. so your "B" print line is waiting. move irt prior the join line.

int main()
{
  std::cout << "A" << std::endl;
  boost::thread threadAlpha(Alpha);
  std::cout << "B" << std::endl;
  threadAlpha.join();
}
stefan
  • 3,681
  • 15
  • 25
0

Calling join will wait until the thread has finished. Don't do that until you've done all the work you can, and need to wait for the thread.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644