jthread 是类成员时的销毁顺序

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

我有一个处理一些线程同步的类。

class ThreadHandler {
    std::vector<std::jthread> threads;
    std::mutex mut;
    std::condition_variable cv;
    int some_int;
    // some other synchronization related variables
};

在 C++ 中,成员析构函数以相反的顺序调用,因此

cv
的析构函数在
threads
的析构函数之前调用。因为
threads
的析构函数加入了
jthread
,所以有一段时间
cv
mut
已被销毁,而
jthread
仍在运行。有问题吗?

c++ multithreading thread-safety c++20 destructor
1个回答
0
投票

感谢评论:

线程被销毁后还能使用cv和mut吗? – 用户253751
代码中的@user253751,是的。线程运行直到 std::stop_token::stop_requested 返回 true,我认为直到调用 join 才会发生这种情况。 – 鲍比

提问者知道代码可以在这些对象被销毁后使用它们。

所以问题是:对象被销毁后还可以使用吗?

答案是:不。

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