[英]crash in std::map clear() - multithreading
我面臨多線程應用程序中的奇怪崩潰:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.