vendredi 26 juillet 2019

Is it safe to use a vector as a queue with multithreading?

Can a vector be written to by multiple threads without worrying about any potential race conditions between the threads trying to push_back a value at the same time? The underlying hardware/os will take care of everything and ensure theres no potential for the program crashing or failing right?

Just wanted to experiment with a simple example that didnt use locks mutexes or atomics.

#include <iostream>
#include<thread>
#include<vector>

using namespace std;

std::vector<int> myvector;


void append(int value)
{
  myvector.push_back(value);
}


int main()
{

 int val1=1;
 int val2=2;
 int val3=3;

 std::thread t1(append,val1);
 std::thread t2(append,val2);
 std::thread t3(append,val3);

 t1.join();
 t2.join();
 t3.join();



 for(int x=0; x<myvector.size(); ++x)
        std::cout<<myvector[x]<<endl;


 return 0;

}

Running the program many times gives expected results of various combinations of push_backs by the threads

Aucun commentaire:

Enregistrer un commentaire