The following code works (i.e., it prints 42
) on all systems I have tried, but I am not sure it is generally valid. My concern is that my_int
is not yet fully constructed and initialized by the time it is read - or am I wrong?
#include <atomic>
#include <iostream>
#include <thread>
#include <functional>
struct MyThread : std::jthread
{
MyThread() : jthread([this] {
std::cout << my_int << std::endl;
}) {};
std::atomic_int my_int = 42;
};
int main()
{
MyThread();
return 0;
}
I find that
Threads begin execution immediately upon construction of the associated thread object
(https://en.cppreference.com/w/cpp/thread/jthread) but I am not 100% certain that means the thread begins execution as soon as the jthread
base object is constructed (which I expect to be correct), or as soon as the MyThread
object is constructed (which I hope is correct).