Open In App

How to Access Vectors from Multiple Threads Safely?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
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:
10
20

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads