Title
Lambda capture and local thread_local variables
Status
nad
Section
7.5.6.3 [expr.prim.lambda.capture]
Submitter
Richard Smith

Created on 2015-07-15.00:00:00 last changed 82 months ago

Messages

Date: 2017-03-15.00:00:00

Rationale (March, 2017):

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

Date: 2022-11-20.07:54:16

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.

Date: 2015-07-15.00:00:00

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.

History
Date User Action Args
2018-02-27 00:00:00adminsetmessages: + msg6003
2018-02-27 00:00:00adminsetmessages: + msg6002
2018-02-27 00:00:00adminsetstatus: concurrency -> nad
2015-07-15 00:00:00admincreate