How to modify value as parameters in lambdas?

Viewed 61

In my program, I have a global static value like this: static bool done=false

which is taken by callback like this:

Library::CallbackType callback(bool& isDone, par1type& par1,....){
    return [&isDone,&par1,...](par0type par0){
        if(conditionTrue){
            doSomething();
        } else {
            thread([isDone,par1]()mutable{
                cleanUp();
                isDone=true;
            }).detach():
        }
    }
}

and the problem is when I call the code:

library->doCallback(callback(done,p1,...));

its code is generally working except the value of done is not changing as I intend. So, what I got wrong?

2 Answers

When you create your thread, you are capturing isDone by value - i.e. the code within the lambda is working on a copy. The mutable keyword doesn't change this, it just lets you change the copy.

The solution is to capture by reference (and then you can drop the mutable):

thread([&isDone,par1](){...
        thread([isDone,par1]()mutable{

This thread is capturing isDone by value. Which means that when it sets isDone to true it will set only its own copy of the original isDone to true.

This thread needs to capture it by reference, too. And, if that's the only reason for this to be a mutable lambda, the mutable can go away as well.

Related