Udostępnij za pośrednictwem


Thread Safety in the Standard C++ Library

The following thread safety rules apply to all classes in the Standard C++ Library (except shared_ptr and iostream classes, as described below).

A single object is thread safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously.

If a single object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected. For example, given an object A, if thread 1 is writing to A, then thread 2 must be prevented from reading from or writing to A.

It is safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given objects A and B of the same type, it is safe if A is being written in thread 1 and B is being read in thread 2.

shared_ptr

Multiple threads can simultaneously read and write different shared_ptr objects, even when the objects are copies that share ownership.

iostream Classes

The iostream classes follow the same rules as the other classes, with one exception. It is safe to write to an object from multiple threads. For example, thread 1 can write to cout at the same time as thread 2. However, this can result in the output from the two threads being intermixed.

Note

Reading from a stream buffer is not considered to be a read operation. It should be considered as a write operation, because this changes the state of the class.

See Also

Reference

Standard C++ Library Overview