Tuesday, March 15, 2011

When to use boost thread join function?

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.

From stackoverflow
  • 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
    Skurmedel : Maybe you should rephrase "is called to terminate a thread". join does not terminate the thread, but makes the current thread wait for the one the join-method was called on. Which I'm sure you are aware of.
    Skurmedel : "wait for the one the join-method was called on to terminate." (SO needs an edit comment button.)
    dirkgently : Yes, and yes again.
  • 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).

  • It may help to show some example code. I will guess that your main() may exit before your thread can print. The join call makes main wait for the thread to complete.

  • Maybe mail thread is finishing...Paste your code, so we can help you

0 comments:

Post a Comment