You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用thread_local修饰类静态unordered_map时程序崩溃的问题求助

thread_local修饰类静态unordered_map时程序崩溃的问题求助

各位好,我遇到了一个关于thread_local修饰类静态unordered_map的崩溃问题,这个案例是从我的项目里简化出来的。我的需求是让每个线程都拥有自己独立的map实例,用来存储各自的键值对,但程序在map执行~_Hashtable()和clear()的时候崩溃了。

以下是我的测试代码:

#include <thread>
#include <unordered_map>
#include <iostream>
#include <cstdio>
using namespace std;

class A {
public:
    void setValue(int idx, int val) {
        a[idx] = val;
    }
    int getValue(int idx) {
        return a[idx];
    }
    size_t getSize() {
        return a.size();
    }
    thread_local static unordered_map<int, int> a;
};

thread_local unordered_map<int, int> A::a = {};

A aa; // 我需要以这种方式使用它

void f(int index) {
    for (int i = 0; i < index; i++) {
        aa.setValue(i, i);
        cout << std::this_thread::get_id() << " " << aa.getSize() << endl;
    }
    for (int i = 0; i < index; i++) {
        cout << "id=" << std::this_thread::get_id() << "n=" << aa.getValue(i) << endl;
    }
}

int main() {
    std::thread t1(f, 3);
    std::thread t2(f, 2);
    t1.join();
    t2.join();
    cout << "Program finished successfully." << endl;
    return 0;
}

我的运行环境是Windows + MinGW64,GCC版本为:gcc.exe (Rev2, Built by MSYS2 project) 12.1.0。

崩溃发生在线程结束时,调用clear()的阶段,对应的STL代码片段如下:

template<typename _Key, typename _Value, typename _Alloc, typename _ExtractKey, typename _Equal, typename _Hash, typename _RangeHash, typename _Unused, typename _RehashPolicy, typename _Traits>
_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _Hash, _RangeHash, _Unused, _RehashPolicy, _Traits>::
~_Hashtable() noexcept {
    // Getting a bucket index from a node shall not throw because it is used
    // in methods (erase, swap...) that shall not throw. Need a complete
    // type to check this, so do it in the destructor not at class scope.
    static_assert(noexcept(declval<const __hash_code_base_access&>()
                  ._M_bucket_index(declval<const __node_value_type&>(), (std::size_t)0)),
                  "Cache the hash code or qualify your functors involved"
                  " in hash code and bucket index computation with noexcept");
    clear();
    _M_deallocate_buckets();
}

有没有大佬能帮我分析下这个问题的原因,以及怎么解决呢?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 11:14:35