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).
This is undefined behavior.
No, that means that the new thread begins executing at some unspecified point after
jthreadis constructed. The only guarantee is that thejthreadwill be constructed when the thread begins execution.Here, in the original execution thread, after the
jthreadbase class gets constructed, then construction begins of the derived class and its members. There is no guarantee, whatsoever, thatjthread's execution begins after the derived class's members are constructed.