简体   繁体   English

Boost :: mutex性能vs pthread_mutex_t

[英]Boost::mutex performance vs pthread_mutex_t

I was using pthread_mutex_t s beforehand. 我之前正在使用pthread_mutex_t 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 不确定代码是如何/在哪里卡住的,我将pthread_mutex_t切换为boost:mutex

1) If i just substitute lines 1 and 3 with boost::lock_guard<boost::mutex> lock(map_mutex); 1)如果我只用boost::lock_guard<boost::mutex> lock(map_mutex);替换第1行和第3行boost::lock_guard<boost::mutex> lock(map_mutex); in line 1, and everything works flawlessly, what could be going wrong with the pthread implementation? 在第1行中,一切都完美无缺,pthread实现可能出现什么问题?

2) Am I giving up performance by switching to boost. 2)我是否通过切换到提升而放弃了性能。 The critical portion here is very time-sensitive so I would like the mutex to be very lightweight. 这里的关键部分是非常时间敏感的,所以我希望互斥体非常轻巧。 (C++, redhat) (C ++,redhat)

  1. If an exception is thrown, or the function returns, between lines 1 and 3, then the mutex will not be unlocked. 如果在第1行和第3行之间抛出异常或函数返回,则互斥锁将不会被解锁。 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. 在Posix平台上, boost::mutex是一个围绕pthread_mutex_t的非常薄的包装器, lock_guard只包含对互斥锁的引用,并在其析构函数中解锁它。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM