3

pthread_mutex_t事先使用了 s 。代码有时会卡住。我有几行代码分散在我包装的函数中......

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

不知道代码是如何/在哪里卡住的,我把它切换pthread_mutex_t到了boost:mutex

1)如果我只是用第 1 行替换第 1 行和第 3boost::lock_guard<boost::mutex> lock(map_mutex);行,并且一切正常,那么 pthread 实现会出现什么问题?

2)我是否通过切换到提升来放弃性能。这里的关键部分对时间非常敏感,所以我希望互斥锁非常轻量级。(C++,红帽)

4

1 回答 1

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.

于 2012-08-21T13:19:11.053 回答