Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using in-place lambda for complex initialisation, especially consts

In-place lambdas can be used for complex initialisation. So you can do something like this:

const widget x = [&]{
    widget val;                                // assume that widget has a default constructor
    for (auto i = 2; i <= N; ++i) {            // this could be some
        val += some_obj.do_something_with(i);  // arbitrarily long code
    }                                          // needed to initialize x
    return val; }();

This is better than writing something like this:

widget x;   // should be const, but:
for (auto i = 2; i <= N; ++i) {             // this could be some
    x += some_obj.do_something_with(i);  // arbitrarily long code
}                                        // needed to initialize x
// from here, x should be const, but we can't say so in code in this style

According to the blog where I read this, the former bit of code is thread safe. This avoids having to use expensive synchronisation. So you wouldn't need to use mutex locking for the latter bit of code to ensure synchronisation.

My question is what makes the former thread safe? How does it work?

like image 658
jignatius Avatar asked Jun 21 '26 08:06

jignatius


1 Answers

I believe that the "blog" referred to the assumption that the usage of a const object should involve only read operations and, therefore, should be safely usable in multiple threads without synchronization. This is the last sentence from that "blog" part:

You can not change its value and, therefore, you can use it in a multithreading program without expensive synchronization.

However, this statement is, generally, incorrect. As pointed out by @VTT, classes may have mutable member variables, or, e.g., reference member variables. There is thus no general guarantee that a const object can be safely used in a multi-threaded code without synchronization.

You may also notice that the corresponding Item ES.28 in C++ Core Guidelines does not mention multi-threading at all in the context of this problem.

like image 175
Daniel Langr Avatar answered Jun 23 '26 22:06

Daniel Langr