Вопрос

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)

Это было полезно?

Решение

  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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top