Junior — Middle
Is the standard Vector container in C++ thread-safe for concurrent access?
sobes.tech AI
Answer from AI
The standard Vector container in C++ is not thread-safe for concurrent access from multiple threads without external synchronization. This means that if multiple threads read and/or modify the same std::vector object simultaneously, the program's behavior will be undefined.
However, if multiple threads only read the vector's contents and no one modifies it, such access is considered safe.
To ensure thread safety during modifications or concurrent access, synchronization mechanisms such as mutexes (std::mutex) should be used.
Example of using a mutex:
#include <vector>
#include <mutex>
std::vector<int> data;
std::mutex mtx;
void thread_safe_push(int value) {
std::lock_guard<std::mutex> lock(mtx);
data.push_back(value);
}
Thus, std::vector itself does not guarantee thread safety.