mardi 13 juin 2023

Capturing a `thread_local` in a lambda

Capturing a thread_local in a lambda:

#include <iostream>
#include <thread>
#include <string>

struct Person
{
    std::string name;
};

int main()
{
    thread_local Person user{"mike"};
    Person& referenceToUser = user;

    // Works fine
    std::thread([&]() {std::cout << "Hello " << referenceToUser.name << std::endl;}).join();

    // Doesn't work
    std::thread([&]() {std::cout << "Hello " << user.name << std::endl;}).join();

    // Works fine
    std::thread([&user=user]() {std::cout << "Hello " << user.name << std::endl;}).join();
}

https://godbolt.org/z/zeocG5ohb

It seems like if I use the original name of a thread_local then its value on the thread which executes the lambda is the thread_local version of the thread which is running the lambda. But as soon as I take a reference or pointer to the thread local it turns into (a pointer to) the originating threads instance.

What are the rules here. Can I rely on this analysis?

Aucun commentaire:

Enregistrer un commentaire