std::vector, thread-safety, multi-threading

Actually, it is absolutely pointless to state X is or is not thread-safe! You need to qualify for what kind of uses. For example, hardly any class will be “thread-safe” when it is somehow used in one thread and destroyed in another.

That said, the statement that std::vector<T> is not thread- safe, independent of how often it is repeated, is wrong. However, it seems most people neither understand nor appreciate the thread-safety guarantees given. std::vector<T> is thread-safe in the following sense:

  • You can read a vector object from multiple threads simultaneously.
  • If there is one thread changing a vector object, there shall be neither concurrent readers or writers.
  • Accesses to a vector object don’t interfere with other vector objects.

This applies to vector structure itself. Accesses to contained object are bound to whatever rules are imposed on them. These are apparently not the thread-safety guarantees many people have in mind but anything stronger won’t work with the container interface.

Leave a Comment