I've run into an issue while multithreading my application, and it appears to come down to not quite understanding how std::vector interacts with a thread.
Generally speaking, I understand that I can have as many concurrent readers as I'd like, and if I have a writer, I should use a std::mutex to lock my thread so no other readers or writers can access my vector while I am writing to it.
However, I have an example where I am only reading using an iterator, and this seems to crash my code.
For example, the following code:
std::vector<int> numbers;
for (int i = 0; i < 100; i++) {
numbers.push_back(std::rand());
}
for (auto& it = numbers.begin(); it != numbers.end(); it++) {
std::cout << "Number : " << (*it) << std::endl;
}
works just fine for printing out a list of random numbers. But if I simply put the second for loop in a thread:
std::vector<int> numbers;
for (int i = 0; i < 100; i++) {
numbers.push_back(std::rand());
}
std::thread([&]() {
for (auto& it = numbers.begin(); it != numbers.end(); it++) {
std::cout << "Number : " << (*it) << std::endl;
}
});
Then this crashes with a Access violation writing location every time. I tried to think of what could go wrong. My first thought was, perhaps numbers is going out of scope, so what if I capture by copy?
std::vector<int> numbers;
for (int i = 0; i < 100; i++) {
numbers.push_back(std::rand());
}
std::thread([=]() {
for (auto& it = numbers.begin(); it != numbers.end(); it++) {
std::cout << "Number : " << (*it) << std::endl;
}
});
Same error. If I create a class and make numbers a member variable, same issue. So it doesn't seem to be an issue with the variable falling out of scope. I even tried performing some logic other than std::cout just in case writing to the console was causing issues, but that isn't it either.
I'm sure that I'm missing some nuance about using std::vector with multiple threads, but I can't quite figure it out -- can anyone point out my mistake?
thanks!