Below sample crashes while thread print is reading the vector and in between the thread insert gets turn and inserts some elements after switching back to thread print program carashes , how to overcome this problem
// Thread_vector.cpp
//
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <thread>
//thead insert
using namespace std;
void insert_elements(vector<int> & v) {
for (int i = 1; i < 20; i++) {
v.push_back(i);
cout << " : inserted - " << i << " ";
}
}
//thead print
void print_elements(vector<int> & vec) {
for (auto & p:vec)
{
std::cout << p << " ";
}
cout << endl;
}
int main()
{
std::vector<int> b;
thread ins(insert_elements, std::ref(b));
thread prn(print_elements, std::ref(b));
ins.join();
prn.join();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire