Boost::mutex performance vs pthread_mutex_t
-
27-06-2021 - |
Вопрос
I was using pthread_mutex_t
s beforehand. The code sometimes got stuck. I had a couple of lines of code scattered across functions that I wrapped...
pthread_mutex_lock(&map_mutex);// Line 1
//critical code involving reading/writing wrapped around a mutex //Line 2
pthread_mutex_unlock(&map_mutex); //Line 3
Not sure how/where the code was getting stuck, I switched the pthread_mutex_t
to a boost:mutex
1) If i just substitute lines 1 and 3 with boost::lock_guard<boost::mutex> lock(map_mutex);
in line 1, and everything works flawlessly, what could be going wrong with the pthread implementation?
2) Am I giving up performance by switching to boost. The critical portion here is very time-sensitive so I would like the mutex to be very lightweight. (C++, redhat)
Решение
If an exception is thrown, or the function returns, between lines 1 and 3, then the mutex will not be unlocked. The next time anyone tries to lock it, their thread will wait indefinitely.
On a Posix platform,
boost::mutex
is a very thin wrapper around apthread_mutex_t
, andlock_guard
just contains a reference to the mutex, and unlocks it in its destructor. The only extra overhead will be to initialise that reference (and even that is likely to be optimised away), and the extra code needed to unlock the mutex in the event of an exception/return, which you'd need anyway.