Question

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?

Was it helpful?

Solution

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top