Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error while using mutex

when I try to make a map that has string as key and pthread_mutex_t as element,

    map<string, pthread_mutex_t> connectedClientsMutexes;

    pthread_mutex_t myMutex;//= PTHREAD_MUTEX_INITIALIZER;
    connectedClientsMutexes.insert(pair<string,pthread_mutex_t>(userName,myMutex));
while (1)
    {

    pthread_mutex_lock(&connectedClientsMutexes[userName]); 
     // do something here 
    }

this generates:

phase3: pthread_mutex_lock.c:312: __pthread_mutex_lock_full: Assertion `(-(e)) != 3 || !robust' failed.

like image 612
Adam Johns Avatar asked Dec 24 '11 23:12

Adam Johns


People also ask

What happens when mutex is locked?

Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

Does mutex prevent deadlock?

Mutexes are used to prevent multiple threads from causing a data race by accessing the same shared resource at the same time. Sometimes, when locking mutexes, multiple threads hold each other's lock, and the program consequently deadlocks.

Can mutex be used across threads?

Mutexes can synchronize threads within the same process or in other processes. Mutexes can be used to synchronize threads between processes if the mutexes are allocated in writable memory and shared among the cooperating processes (see mmap(2)), and have been initialized for this task.

Can a mutex be locked twice?

To solve your issue, you can use std::recursive_mutex , which can be locked/unlocked multiple times from the same thread.


1 Answers

It is undefined to copy a mutex. Try putting a pointer to the mutex in the map.

EDIT That's the nature of undefined behavior. Sometimes you get lucky (or seem to) and sometimes you don't.

Instead of copies of multiple mutexes in the map you put multiple pointers to the mutexes instead. So something like:

map<string, pthread_mutex_t *> connectedClientsMutexes;

connectedClientsMutexes.insert(pair<string,pthread_mutex_t *>(userName, &myMutex));

pthread_mutex_lock(connectedClientsMutexes[userName]);

Presumably you are passing the map around to various threads so it would be wise not to allocate those mutexes on the stack unless you are positive they aren't going to go out of scope. Declare them as globals or dynamically allocate them and initialize them with pthread_mutex_init().

like image 74
Duck Avatar answered Oct 30 '22 20:10

Duck