2

I'm facing with a strange crash in a multithreaded application:

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

where lock and unlock are:

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

The crash occurrence is very rare and hard to predict a scenario to reproduce it. The mutexes should guarantee that the map is not altered from a thread to another, right?

1 Answers1

8

My guess would be that you are copying your mutex, and maybe this stops it from working as one. Try using a pointer:

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

Edit

Or, it seems that a reference would also work:

int lock(pthread_mutex_t& mutex)
{
    return pthread_mutex_lock(&mutex);
}
int unlock(pthread_mutex_t& mutex)
{
    return pthread_mutex_unlock(&mutex);
} 
Maksim Solovjov
  • 3,147
  • 18
  • 28