Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost::mutex performance vs pthread_mutex_t

I was using pthread_mutex_ts 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)

like image 672
Joshua Avatar asked Dec 14 '25 05:12

Joshua


1 Answers

  1. 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.

  2. On a Posix platform, boost::mutex is a very thin wrapper around a pthread_mutex_t, and lock_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.

like image 62
Mike Seymour Avatar answered Dec 15 '25 18:12

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!