I guess this problem has appeared already and it surely shows my beginner level in the world of threads, but I haven't been able to find any previous question nor other resource addressing it. I've gone through the most common introductions to C++11 threads (such as this, this and this) but it didn't help.
Here is my code:
mutex mtx;
vector<thread> threads;
for(vcit = vc.begin(); vcit != vc.end(); ++vcit) {
const std::shared_ptr<Graph> g = graphs.at(*vcit);
cout << "Graph (outside thread): " << g->name << endl;
threads.push_back(thread(
[&g, &mtx] () {
lock_guard<mutex> guard(mtx);
cout << "Graph (inside thread): " << g->name << endl;
}
));
}
for(thread& t : threads) {
t.join();
}
I would expect each thread to receive a different pointer, but instead the output of the program is as follows (for 2 elements in vector vc
):
Graph (outside thread): ABC
Graph (outside thread): DEF
Graph (inside thread): DEF
Graph (inside thread): DEF
Occasionally the program would "work" and output:
Graph (outside thread): ABC
Graph (inside thread): ABC
Graph (outside thread): DEF
Graph (inside thread): DEF
(notice the mixed order of output from outside and inside now). I tried to move from a lambda to a functor object, but that was of no help and the program exhibited the same behaviour.
I'd like to know where the problem lies with the code and also where my understanding of how threads (or shared_ptr's perhaps) work is flawed, if this is deducible from the code.