STL containers and thread safety
When discussing STL containers, assuming a blanket level of thread safety across all of them is tempting. However, such assumptions can be misleading. By default, STL containers are not thread-safe for modifications, meaning if one thread modifies a container, other threads simultaneously accessing it might lead to undefined behavior.
However, some inherent guarantees exist. For instance, it is safe for multiple threads to simultaneously read from an STL container, as long as no thread is modifying it. This is often referred to as read concurrency. Yet, the moment even a single thread tries to change the container while others read, we’re back in the dangerous territory of race conditions.
When safety needs reinforcements – concurrent modifications
While reading concurrently is safe, modifications bring a different set of challenges. Suppose two or more threads attempt to modify an STL container simultaneously. In that case, the...