在 std::map clear() 中崩溃 - 多线程

Posted

技术标签:

【中文标题】在 std::map clear() 中崩溃 - 多线程【英文标题】:crash in std::map clear() - multithreading 【发布时间】:2015-10-25 08:59:12 【问题描述】:

我在多线程应用程序中遇到了奇怪的崩溃:

static std::map<int, std::string> g_params;

Thread 1
    (void)lock(map_mutex);
    g_params[iParamID] = sValue;
    (void)unlock(map_mutex);

Thread 2
    (void)lock(map_mutex);
    std::map<int, std::string>::iterator it;
    for (it = g_params.begin(); it != g_params.end(); ++it)
    
        // process it->first and it->second, w/o modifying them
    
    g_params.clear(); //  the crash occurs here: #5  0x76a3d08c in *__GI___libc_free (mem=0x703070c8) at malloc.c:3672
                      //#14 std::map<int, std::string, std::less<int>, std::allocator<std::pair<int const, std::string> > >::clear (this=0xb4b060)
    (void)unlock(map_mutex);

其中 lockunlock 是:

int lock(pthread_mutex_t mutex)

    return pthread_mutex_lock(&mutex);

int unlock(pthread_mutex_t mutex)

    return pthread_mutex_unlock(&mutex);
 

崩溃的发生非常罕见,很难预测重现它的场景。互斥锁应该保证映射不会从一个线程更改到另一个线程,对吧?

【问题讨论】:

您是按值传递,并获取临时地址。效果不太好…… 【参考方案1】:

我的猜测是您正在复制您的互斥锁,这可能会阻止它作为一个互斥锁工作。尝试使用指针:

int lock(pthread_mutex_t* mutex)

    return pthread_mutex_lock(mutex);

int unlock(pthread_mutex_t* mutex)

    return pthread_mutex_unlock(mutex);
 

编辑

或者,似乎引用也可以:

int lock(pthread_mutex_t& mutex)

    return pthread_mutex_lock(&mutex);

int unlock(pthread_mutex_t& mutex)

    return pthread_mutex_unlock(&mutex);
 

【讨论】:

以上是关于在 std::map clear() 中崩溃 - 多线程的主要内容,如果未能解决你的问题,请参考以下文章

std::unordered_map::clear() 做啥?

c++ map clear相关内存会清空吗?

c++ map clear相关内存会清空吗

PyQt QTreeWidget.clear() 导致崩溃

C++ map 如何清空 内存泄露

C++ map 如何清空 内存泄露