This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 115e. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-11-11


2159. Lambda capture and local thread_local variables

Section: 7.5.6.3  [expr.prim.lambda.capture]     Status: NAD     Submitter: Richard Smith     Date: 2015-07-15

Consider the following example:

  void f() {
    thread_local int n = 10;
    std::thread([&] { std::cout << n << std::endl; }).join();
  }

This function prints 0, because:

  1. The lambda does not capture n

  2. n is not initialized on the spawned thread prior to the invocation of the lambda.

Additional note, March, 2016:

SG1 discussed this issue and concluded that the issues should be resolved follows:

  1. If the program would result in a capture by reference of a local thread-local variable, then it is ill-formed.

  2. If the program has a capture by value of a local thread-local variable, then a copy of the value from the calling thread is captured (and initialized in the calling thread, if necessary).

The rationale for #1 is that, if we allowed capture of local thread-locals, some programmers will have one intuition of what to expect and other programmers will have the opposite intuition. It's better to forbid both interpretations. We don't want to say simply that there is no capture by reference of thread-locals, because simply ignoring the local thread-local might result in name-lookup finding a global variable by the same name, which would be very confusing.

Rationale (March, 2017):

Only automatic variables are captured. A lambda accessing a thread-local variable would be ill-formed.