As highlighted by @R.. in the comments, this appears to be a bug in the implementation of glibc (assuming you are using Linux -- I can reproduce this on Linux 2.17 compiled with GCC 4.9.1), in that exit()
doesn't ensure, while flushing and closing streams, there's no race when it's called by one thread when multiple threads use stdout.
The following from flockfile
manual clearly indicates that the behaviour observed is not correct:
The stdio functions are thread-safe. This is achieved by
assigning to each FILE object a lockcount and (if the lockcount is
nonzero) an owning thread. For each library call, these functions
wait until the FILE object is no longer locked by a different
thread, then lock it, do the requested I/O, and unlock the object
again.
In light of this, the following options can be considered as a workaround (as there's no response to the bug report) to this particular case that we observed here.
Both the threads "share" the stdout
stream and I think, the "extra" output is printed because of the premature exit of main thread.
printf
buffers (in sample_thread()
) the output and before it could clear it's buffer (due to
in printfs), main thread exits. Hence forcing the flush of stdout
buffer when the process exits.
To fix,
1) you could call setbuf()
in main()
before creating the thread:
setbuf(stdout, NULL);
to not buffer stdout
at all.
Or
2) call pthread_exit()
in both threads so that the process continues if either thread dies.
Or
3) call pthread_join()
in main thread so that main thread waits for the completion of sample_thread
thread.
Either one of these will avoid the issue.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…