gpt4 book ai didi

c++ - 如何正确处理 pthread 互斥量?

转载 作者:行者123 更新时间:2023-11-28 02:46:02 24 4
gpt4 key购买 nike

我写了一个类来包装互斥体。在析构函数中,我调用 pthread_mutex_destroy 有时它会返回 EBUSY 因为其他线程还没有释放它。我的问题是,处理互斥体销毁的最佳方法是什么?我应该等它免费吗?

这是我目前所拥有的,可能不是最好的解决方案:

Mutex::~Mutex()
{
int rc = pthread_mutex_destroy( &_mutex );
while ( rc == EBUSY )
{
lock(); // Call to pthread_mutex_lock
unlock(); // Call to pthread_mutex_unlock

// Attempt destroy again
rc = pthread_mutex_destroy( &_mutex );
}
}

最佳答案

My question is, what is the best way to handle the destruction of a mutex? Should I wait for it to be free?

您不应该在使用资源时销毁它们,因为这通常会导致未定义的行为。

正确的做法是:

  • 告诉其他线程释放资源并等待,或者
  • 礼貌地告诉其他线程终止并等待它完成,或者
  • 将资源的所有权传递给另一个线程,让它随意管理资源的生命周期,或者
  • 使用共享资源,让它们在用户还在的时候保持活力。

关于c++ - 如何正确处理 pthread 互斥量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24410030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com