c++ - 如何使用 pthread_mutex_destroy 安全地销毁互斥锁

标签 c++ multithreading synchronization pthreads mutex

我有一个包含一些逻辑并有一个工作线程的类,有几个函数可以检查到目前为止完成的工作的状态。 我将更改包装到内部数据并使用互斥锁进行检查,api 要求有一个信号函数告诉类开始关闭,这意味着不能处理新请求,但只要旧请求仍然存在关于进度,可以检查他们的状态。

我的问题是我很难决定何时安全地销毁互斥锁​​,因为在我解锁它的那一刻,可能有另一个线程试图检查某个作业的状态,我最终会销毁一个锁定的互斥锁是不好的。 有什么建议么?

  • 编辑:这行得通吗? ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { pthread_mutex_unlock(&om); pthread_mutex_destroy(&om); } (使用 asm/atomic.h 中的宏)*

不应该像看起来那样使用...

编辑 2:

假设我有以下功能:

void queue_image(image pic){
     pthread_mutex_lock(&mo);
     // add 
     pthread_mutex_unlock(&mo);
}

void is_pic_processed(string pic_id){
    pthread_mutex_lock(&mo);
     // chech whether pic was processed
     pthread_mutex_unlock(&mo);
}

void * process(void* arg){ //this is in another thread
    while(1){
      pthread_mutex_lock(&mo);
      if(kill_flag && no more work){ 
         pthread_mutex_unlock(&mo);
(1)      /* the problem is here because in the meanwhile 
            someone could've called is_pic_processed locked the mutex 
            and now I'm destroying a locked mutex which is undesirable */
         pthread_mutex_destroy(&mo);
      }
      // do more work 
      pthread_mutex_unlock(&mo);
    }
}

void kill(){ // has to return and not wait for the remaining processing to take place
     pthread_mutex_lock(&mo);
     // set flag to end the work 
     pthread_mutex_unlock(&mo);
}

kill 只是停止处理而不是整个应用程序,我对其他线程调用 is_pic_processed 没有问题 after 互斥量的破坏并得到适当的错误我有问题在首先尝试销毁互斥量时调用,希望这能稍微解决问题。

最佳答案

我不明白这个问题。只要仍有“进行中”的请求,您就不应该销毁互斥量。

工作线程本身应该检查请求队列,如果调用了“关闭”函数,它应该销毁互斥锁​​,并且大概会死掉。

所以:

  • 没有人会尝试锁定互斥量,因为所有请求都已处理并且没有正在进行的请求
  • 一旦锁定并销毁它的线程是同一个线程,就可以安全地销毁它

希望我正确理解了这个问题:)

在您的编辑 2 之后

您添加的内容与您之前所说的内容冲突:

as long as the old ones are still on progress, it's OK to check their status.

您现在是说即使他们不再“进行中”,也可以检查他们的状态。

无论如何,这不是问题。因为您可以调用 pthread_mutex_destroy 而无需之前调用 pthread_mutex_unlock

我用这个作为来源The Open Group Base Specifications Issue 7 - pthread.h

编辑 3: 我想在我的答案中添加一些内容:您需要在此处进行一些重新设计。

即使您可以在该互斥锁被锁定时销毁它,您也需要确保在它被销毁后没有其他线程可以尝试锁定它,例如通过检查您现在完成的请求的状态。

换句话说,如果你想销毁互斥锁​​,那么在设置“kill flag”之后,就不能使用互斥锁检查请求的状态。

关于c++ - 如何使用 pthread_mutex_destroy 安全地销毁互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021845/

相关文章:

c++ - 具有通用索引类型的数组

java - Java中线程访问非同步方法

c# - 沙盒 AppDomain 中的线程安全

c++ - 关闭 MFC 对话框时的多线程对象销毁

cocoa-touch - Wifi与核心资料库样式同步

c++ - 使用fopen创建新文件时如何设置FILE*对象编码格式?

c++ - 如何将中文/韩文单词导出到csv

c++ - 将数组推回矩阵 C++

c# - SynchronizationContext.CreateCopy 的目的

c++ - 有时可以在 C++ 中使用 std::atomic 代替 std::mutex 吗?