1

Suppose I have code like such:

main() {
    start thread;
    put data in task queue;
    do some stuff
    wait for data in result queue;
    printf ("main got result\n");
    fflush(stdout);
}

thread() {
    while (!done) {
        wait for data in task queue;
        printf ("thread finished processing\n");
        fflush(stdout);
        put data in result queue;
    }
}

Is it possible to get output like the following if my thread-safe data queues are working properly?

main got result
thread finished processing

Can stdio get reordered like that, or is that a sure sign that my "thread-safe" queues aren't?

Does the answer change if I am compiling with C++ and using iostreams in the "do some stuff" section of main (but still using printf where shown) in the code above?

2
  • It's unlikely that such reordering happens, but it could be implementation-dependant. You are printing and flushing stdout in the thread before adding data to the result queue. It's a mode likely bet to assume you have some synchronization problems with the queues.
    – Ivan Voras
    Oct 11, 2013 at 16:28
  • In my case it was indeed caused by me misunderstanding what conditions could cause "wait for data in queue" to unblock prematurely. Modifying my return-value checking for that function fixed the problem. Thanks guys, you put me on the right track for debugging the problem.
    – pavon
    Oct 11, 2013 at 19:19

1 Answer 1

1

Nope.

Even you are running two threads asynchronously (I don't know if you are here), inside each thread the commands are executed in order.

So, your thread() would print "tread finished processing" first, then put data in result queue. Only then will your main() get the message and print the "main got result".

2
  • Okay. That is what I understood from years of C programming, but I have seen all sorts of weirdness mixing iostream and stdio, and am still not completely confident in my understanding of the buffering/syncing that goes on between those two.
    – pavon
    Oct 11, 2013 at 16:33
  • I'm just speaking from experience. I can't think of any possible way that the two outputs would be swapped. But who knows, some bizarre condition things could happen. Oct 11, 2013 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.