Ensuring thread safety of stream objects

All classes declared in the iostream standard library are reentrant, and use a single lock to ensure thread-safety while preventing deadlock from occurring. However, on multiprocessor machines, there is a chance, although rare, that livelock can occur when two different threads attempt to concurrently access a shared stream object, or when a stream object holds a lock while waiting for input (for example, from the keyboard). If you want to avoid the possibility of livelock, you can disable locking in input stream objects, output stream objects, or both, by using the following macros at compile time:

__NOLOCK_ON_INPUT
Disables input locking.
__NOLOCK_ON_OUTPUT
Disables output locking.
To use one or both of these macros, prefix the macro name with the -D option on the compilation command line. For example:
xlC_r -D__NOLOCK_ON_INPUT -D__NOLOCK_ON_OUTPUT a.C
Alternatively, you can disable locking in input stream objects, output stream objects, or both, by using the following environment variables at run time:
XLCPP_NOLOCK_ON_INPUT
Disables input locking.
XLCPP_NOLOCK_ON_OUTPUT
Disables output locking.
For example, you can use the following command to disable locking in input stream objects:
export XLCPP_NOLOCK_ON_INPUT=1

It is recommended that you use the environment variables to disable locking in stream objects.

However, if you disable locking on input or output objects, you must provide the appropriate locking mechanisms in your source code if stream objects are shared between threads. If you do not, the behavior is undefined, with the possibility of data corruption or application crash.

Note: If you use OpenMP directives or the -qsmp option to automatically parallelize code which shares input/output stream objects, in conjunction with the lock-disabling macros, you run the same risks as with code that implements Pthreads or other multithreading constructs, and you will need to synchronize the threads accordingly.