How to Access Vectors from Multiple Threads Safely?
Last Updated :
06 Mar, 2024
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++
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
using namespace std;
vector< int > myVector;
mutex mtx;
void addToVector( int value)
{
lock_guard<mutex> lock(mtx);
myVector.push_back(value);
}
int main()
{
thread t1(addToVector, 10);
thread t2(addToVector, 20);
t1.join();
t2.join();
cout << "Vector elements: " ;
for ( int value : myVector) {
cout << value << " " ;
}
cout << endl;
return 0;
}
|
Output
Vector Elements:
10
20
Share your thoughts in the comments
Please Login to comment...