EN VI

C++ - Can I access the value of a derived-class member in a function running in a std::jthread from which I derive?

2024-03-14 18:30:04
C++ - Can I access the value of a derived-class member in a function running in a std::jthread from which I derive?

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).

Solution:

This is undefined behavior.

I am not 100% certain that means the thread begins execution as soon as the jthread base object is constructed

No, that means that the new thread begins executing at some unspecified point after jthread is constructed. The only guarantee is that the jthread will be constructed when the thread begins execution.

Here, in the original execution thread, after the jthread base class gets constructed, then construction begins of the derived class and its members. There is no guarantee, whatsoever, that jthread's execution begins after the derived class's members are constructed.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login