Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use boost thread join function?

Tags:

c++

join

boost

I've recently managed to create a thread using the boost::bind function.

For the time being, I'm having the thread display to stdout. I can see the output if I use thread.join. However, if I don't do this, I don't see any output.

Why is this?

I'm hoping I don't have to use the join function, because I would like to call this function multiple times, without having to wait for the previously launched thread to finish.

Thanks for your responses. What I really wanted to make sure of was that the thread actually executed. So I added a system call to touch a non-existent file, and it was there afterwards, so the thread did execute.

like image 790
Jack BeNimble Avatar asked Nov 24 '25 06:11

Jack BeNimble


2 Answers

I can see the output if I use thread.join. However, if I don't do this, I don't see any output. Why is this?

Most probably this is a side-effect of the way standard output is buffered on your system. Do you have '\n' and/or endl sprinkled around in every print statement? That should force output (endl will flush the stream in addition).

If you look at the documentation for join, you'd see that this function is called to wait till until termination of the thread. When a thread is terminated (or for that matter, a process) all buffered output is flushed.

You do not need to wait till the thread has completed execution in order to see output. There are at least a couple of ways (I can remember off the top of my head) you can achieve this:

  • Make cout/stdout unbuffered, or
  • Use \n and fflush(stdout) (for C-style I/O) or std::endl stream manipulator
like image 129
dirkgently Avatar answered Nov 26 '25 20:11

dirkgently


By default the thread object's destructor does not join to the main thread, could it be that your main thread terminates and closes STDOUT before the thread manages to flush its output?

Note that in C++0x the default destructor for thread does join (rather than detach as in boost) so this will not happen (see A plea to reconsider detach-on-destruction for thread objects).

Note: Since this was written the C++11 standard was changed and an unjoined thread now terminates the process.

like image 22
Motti Avatar answered Nov 26 '25 20:11

Motti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!