I have following block of code, what I expected is the i inside the lambda capture list is passed by value and the i be outputted should be different.
However, the actual result is the output 20 lines of 19 is completed.
I tried to change the this line std::thread t([&func](){ to std::thread t([func](){, the output could print different i value.
My question is why std::thread t([&func](){ and std::thread t([func](){ will lead the different output value of i?
void DoSomething(std::function<void()> func)
{
std::thread t([&func](){
//do something
sleep(1);
if (func)
func();
});
t.detach();
}
int main(int argc, const char * argv[]) {
std::mutex mtx;
for (int i = 1 ; i < 20; i ++) {
DoSomething([i, &mtx](){
std::unique_lock<std::mutex> lock(mtx);
std::cout << i << " is completed" << std::endl;;
});
}
sleep(10);
}