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

C++ std::map clear()中崩溃-多线程,c++,multithreading,crash,mutex,stdmap,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>::itera

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

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

这次坠机事件非常罕见,很难预测一个情景来重现它。互斥体应该保证映射不会从一个线程更改到另一个线程,对吗?

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

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

您通过值传递,并获取临时地址。那不太好。。。
int lock(pthread_mutex_t& mutex)
{
    return pthread_mutex_lock(&mutex);
}
int unlock(pthread_mutex_t& mutex)
{
    return pthread_mutex_unlock(&mutex);
}