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

时间:2015-08-03 09:43:09

标签: c++ multithreading crash mutex stdmap

我在多线程应用程序中面临一个奇怪的崩溃:

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);

其中 lock unlock 是:

int lock(pthread_mutex_t mutex)
{
    return pthread_mutex_lock(&mutex);
}
int unlock(pthread_mutex_t mutex)
{
    return pthread_mutex_unlock(&mutex);
} 

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

1 个答案:

答案 0 :(得分:7)

我的猜测是你正在复制你的互斥锁,也许这会阻止它作为一个整体工作。尝试使用指针:

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