我可以访问在我派生的 std::jthread 中运行的函数中的派生类成员的值吗?

问题描述 投票:0回答:1

以下代码在我尝试过的所有系统上都有效(即,它打印

42
),但我不确定它是否普遍有效。我担心的是
my_int
在读取时尚未完全构造和初始化 - 还是我错了?

#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;
}

我发现了

线程在构造关联的线程对象后立即开始执行

(https://en.cppreference.com/w/cpp/thread/jthread)但我不能100%确定这意味着一旦构造了

jthread
基础对象(我期望是正确的),或者一旦构造了
MyThread
对象(我希望是正确的)。

c++ multithreading derived-class
1个回答
2
投票

这是未定义的行为。

我不能 100% 确定这意味着线程一旦开始执行 jthread 基础对象已构造

不,这意味着新线程在构造

jthread
后在某个未指定的点开始执行。唯一的保证是当线程开始执行时将构造
jthread

这里,在原始执行线程中,在构造完

jthread
基类之后,就开始构造派生类及其成员。无论如何,都不能保证
jthread
的执行是在派生类的成员构造完成之后开始的。

© www.soinside.com 2019 - 2024. All rights reserved.