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.
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.
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.
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.
To solve your issue, you can use std::recursive_mutex , which can be locked/unlocked multiple times from the same thread.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With