I'm supposing that you're asking about multiple MPI processes all writing to the same device, perhaps a terminal. To the extent that you're interested in the output of multiple threads of individual processes, @JonathanLeffler's answer will be of great interest to you.
The C language does not speak to the question of separate processes' effects on each others' use of the same device. It is scoped to the behavior of individual runs of individual programs. For POSIX, and I suspect Windows as well, it depends to some extent on how it comes to pass that the multiple separate MPI processes even have the ability to write to the same device at the same time, if indeed that does come to pass.
If the processes have opened the device separately, then the behavior you can rely upon depends on the device and its driver, possibly on the characteristics of the data being printed, and possibly also on details of how the device was opened by each process. I would generally expect that for a given machine and device, there would be a characteristic size (larger than 1) such that data of that size or smaller written in one go by one process will not be commingled with data from other processes, but I am not aware of specific documentation promising that in general, or detailing what such characteristic sizes would be.
Under POSIX, if sharing a device arises from inheriting an open file description from a common ancestor (shell, master process, etc.), then in addition to the above considerations, POSIX places some requirements, detailed in section 2.5.1. Inasmuch as your example involves writing to stderr
, which is unbuffered by default, your usage will satisfy those requirements as long as you have not changed its (non-)buffering. In that event, POSIX promises that
regardless of the sequence of handles used, implementations shall ensure that an application, even one consisting of several processes, shall yield correct results: no data shall be lost or duplicated when writing, and all data shall be written in order, except as requested by seeks. It is implementation-defined whether, and under what conditions, all input is seen exactly once.
And that's all, though it's still more than you have in the other case. "Written in order" does not guarantee that data from different writes will be segregated. In practice, however, each fprintf
call will make write()
requests to the underlying system, transferring the printed data in one or a few chunks, and, again in practice, each chunk will be written contiguously.
So,
it is not guaranteed by C or POSIX that multiple processes' writes to the same device will be serialized with respect to each other. Windows may make stronger guarantees, but I'm not prepared to speak to that.
it is nevertheless unsurprising that you see such serialization in practice.