thread_local + std::thread 销毁时死锁

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

有人知道这是什么类型的UB吗?使用 MSVC 19.29.30148 构建时,以下代码在

jthread
销毁上死锁,有时在 std::cout 之后死锁,有时在之前死锁。 这在某种程度上与 thread_local 有关,但我看不出问题是什么。它似乎在其他编译器和平台下工作得很好。

#include <thread>
#include <memory>
#include <iostream>

int main(void)
{
    std::thread t2(
        [&] {
            thread_local std::jthread asd([] {
                    std::cout << "ASD" << std::endl;
                    });
        });
    if (t2.joinable()) { t2.join(); }
}

更新:在静态和动态运行时均可重现

c++ multithreading c++20 msvcrt compiler-bug
1个回答
0
投票

我的猜测是,你已经发现了这种情况,即假设在破坏时安全地

jthread
join()
永远不会被破坏。与
thread
不同,
jthread
可以在没有隐式连接/分离的情况下使用。假设在某个时刻发生的任何事情都会被销毁,因此不会调用终止连接。此代码将调用终止:
jthread

但是
int main(void) { std::thread t2( [&] { thread_local std::thread asd([] { //simple thread std::cout << "ASD" << std::endl; }); }); if (t2.joinable()) { t2.join(); }//since asd not joined/detached it will be terminated }

不会终止。因为

jthread asd
不会在
thread_local asd
之前被销毁。而
t2.join()
又不能
t2
因为在某些
join
中既没有加入也没有分离并且没有终止。
    

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