ciostdoutfwrite

Is fwrite() atomic when applied to multiple FILE*, same file descriptor?


  1. using fileno() to get the actual file descriptor of stdout.
  2. using fdopen() to create two different FILE* structure, named a and b.
  3. creating two threads, name A and B, using fwrite() to write some contents to a and b.

Question:

  1. Is this operation correct, or recommended?
  2. If A thread is writing 123, B thread is writing 456, is it possible that 142536 got output in the stdout?

Solution

  • Maybe have a look here: fopen and fwrite to the same file from multiple threads

    Better define another thread, which is taking control over the file and implement a queue like structure that other tasks can fill with data.

    The file thread will then pop (think FIFO) data from the structure and write it to the file.