Thread catching reference or copy of a shared pointer, got a bizarre problem here?

Viewed 49

Just see the demo I write below:

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <unistd.h>
using namespace std;

class SomethingWithVec
{
public:
    SomethingWithVec() {}
    void push(int num)
    {
        lock_guard lock(mutex_);
        v_.push_back(num);
    }
    int size()
    {
        lock_guard lock(mutex_);
        return v_.size();
    }

private:
    vector<int> v_;
    mutex mutex_;
};

int main(int argc, char **argv)
{
    vector<thread> threads;
    vector<shared_ptr<SomethingWithVec>> vecs;
    for (int i = 0; i < 4; i++)
    {
        auto sth = make_shared<SomethingWithVec>();
        threads.emplace_back([&sth]()
                             {
                                 while (true)
                                 {
                                     this_thread::sleep_for(2000ms);
                                     printf("size at thread[%d] is %d\n", gettid(), sth->size());
                                 }
                             });
        vecs.push_back(sth);
    }
    vecs[1]->push(1);
    for (int i = 0; i < 4; i++)
        threads[i].join();
    return 0;
}

I create a class SomethingWithVec supporting concurrently r/w using mutex. And in the main function, I create 4 threads catching the reference of a corresponding shared pointer of SomethingWithVec. And then I modify one of the SomethingWithVecs outside. I expect to see that one of the threads print "size = 1", but got the following output:

size at thread[30819] is 0
size at thread[30822] is 0
size at thread[30821] is 0
size at thread[30820] is 0

It seems nothing happened after pushing a value to vecs[1].

I struggled with this for quite a while, but once I change the [&sth] to [sth], the output seems perfectly right:

size at thread[31595] is 0
size at thread[31597] is 0
size at thread[31598] is 0
size at thread[31596] is 1

Just can't figure out why? This is really weird, am I missing something fundamental?

0 Answers
Related