How to Access Vectors from Multiple Threads Safely? Last Updated : 23 Jul, 2025 Comments Improve Suggest changes 1 Likes Like Report In C++, a thread is a basic element of multithreading that represents the smallest sequence of instructions that can be executed independently by the CPU. In this article, we will discuss how to access a vector from multiple threads safely in C++. Safely Access Vectors from Multiple Threads in C++To access vectors from multiple threads safely, use a mutex to synchronize access to the vector. Acquire the mutex before performing any read or write operations and release it afterward. Ensure that all threads accessing the vector use the same mutex to prevent concurrent access. C++ Program to Access Vectors from Multiple Threads Safely C++ // C++ Program to illustrate how to access vectors from // multiple threads safely #include <iostream> #include <mutex> #include <thread> #include <vector> using namespace std; vector<int> myVector; // Mutex for safe access to the vector mutex mtx; // Function to add an element to the vector safely void addToVector(int value) { lock_guard<mutex> lock(mtx); // Acquire the mutex myVector.push_back(value); // Add element to the vector } int main() { // Create two threads to concurrently add elements to // the vector thread t1(addToVector, 10); thread t2(addToVector, 20); t1.join(); t2.join(); // Display the elements of the vector cout << "Vector elements: "; for (int value : myVector) { cout << value << " "; } cout << endl; return 0; } Output Vector Elements:1020 Create Quiz Comment S susobhanakhuli Follow 1 Improve S susobhanakhuli Follow 1 Improve Article Tags : C++ Programs C++ STL cpp-vector cpp-multithreading CPP Examples +2 More Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like