3

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)

Joshua
  • 1,516
  • 2
  • 22
  • 31

1 Answers1

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

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • OK Thanks. I figured it was a thin wrapper, but I couldn't find anyone who had already done a study anywhere. As for the first part, the rest of the program keeps running just fine. So if there are no return statements where line 2 is, how would I know if an exception has been thrown? – Joshua Aug 21 '12 at 13:22
  • @Joshua: You can tell if an exception has been thrown by reporting it from the `catch` block. If you're not catching it, then the program will terminate if you're using `boost::thread` or `std::thread`; if you're using `pthread_create` directly, then you'll get undefined behaviour (in practice, I think the thread silently stops), so in that case you really should add a `catch` block to the thread's top-level function. – Mike Seymour Aug 21 '12 at 13:33