Imagine the following scenario:
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
void DoSomething(int* i)
{
std::cout << *i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
*i = 2;
std::cout << *i << std::endl;
}
int main()
{
std::vector<int> v = {0, 0, 0};
v[0] = 1;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::thread t(&DoSomething, &v[0]);
t.join();
std::cout << v[0] << std::endl;
}
Is there any reason that there should be a mutex passed along with the vector element?
P.D. from 08/May/2015
I did not elaborate on the question more when posting, since I didn't want to influence the answer. What you've answered would have been pretty much my understanding till yesterday. However, it has been suggested to me that intuitive behaviour might not be serviceable in threading scenarios as much as one would hope. Particularly, in this case, it has been suggested that, for instance, the assumption that the writing v[0] = 1 happening on the main thread is something that, without a mutex, will be reflected when printing in DoSomething is not guaranteed. As a possible explanation I was offered that the value might go into thread accessible memory, but that it might be swapped out by the state of a different thread before it is written to cross-thread memory, and again, that the only way of guaranteeing the desired propagation would be using a mutex. What is your opinion on that argument?