Interview Question
It depends on the implementation. There are some guarantees, but the implementation is not forced to use a mutex.
The C standard I/O library (stdio) documentation states that each call to printf(), scanf(), getchar(), putchar(), and any other stdio functions behave as if a call to flockfile(3) was made before invoking the specified function and a call to funlockfile(3) was made after invocation.
So, stdio is thread safe, as long as the threads are well behaved and use the accepted, known interface to deal with file streams - the stdio library.
The same guarantees apply to C++, but note that things like
cout << "Hello" << " World";
is actually 2 calls, so this is not atomic.
Note, however, that stdio and any I/O library uses the read(2) and write(2) syscalls under the hood, which are not atomic. If a misbehaving process neglects to use stdio and starts reading and writing with read(2) and write(2), then things can start to break even if everyone else uses stdio to manipulate the file.
So, in short, as long as you use the library, you are mostly safe, but an important point to mention to the interviewer is that the exact implementation details of how stdio manages locking are very platform specific and don't necessarily rely on a mutex.
It depends on the implementation. There are some guarantees, but the implementation is not forced to use a mutex.
The C standard I/O library (stdio) documentation states that each call to printf(), scanf(), getchar(), putchar(), and any other stdio functions behave as if a call to flockfile(3) was made before invoking the specified function and a call to funlockfile(3) was made after invocation.
So, stdio is thread safe, as long as the threads are well behaved and use the accepted, known interface to deal with file streams - the stdio library.
The same guarantees apply to C++, but note that things like
is actually 2 calls, so this is not atomic.
- Anonymous July 09, 2015Note, however, that stdio and any I/O library uses the read(2) and write(2) syscalls under the hood, which are not atomic. If a misbehaving process neglects to use stdio and starts reading and writing with read(2) and write(2), then things can start to break even if everyone else uses stdio to manipulate the file.
So, in short, as long as you use the library, you are mostly safe, but an important point to mention to the interviewer is that the exact implementation details of how stdio manages locking are very platform specific and don't necessarily rely on a mutex.