gpt4 book ai didi

linux - 如何在 Linux 中摆脱死锁

转载 作者:太空狗 更新时间:2023-10-29 12:14:08 24 4
gpt4 key购买 nike

在多线程系统上,如果两个线程在锁定一个互斥锁后想在共享内存上工作。

线程 A:

pthread_mutex_lock(&mutex)  
....... //Memory corruption or Assert and thread exits
pthread_mutex_unlock(&mutex)

线程 B:

pthread_mutex_lock(&mutex)  
.......
pthread_mutex_unlock(&mutex)

如果线程 A 首先获取互斥量并由于内存损坏或断言而退出,线程 B 将永远等待导致死锁。

  1. 一旦发生这种僵局,我是否可以使用某种方式/方法来摆脱这种僵局?
  2. 我可以使用与互斥量类似的其他更安全的方法吗?

最佳答案

您可以在互斥体上设置ROBUST 属性。对于健壮的互斥锁,如果获取它的线程由于某种原因退出而没有解锁它,互斥锁会进入一种特殊状态,在该状态下,下一个尝试锁定它的线程将获得 EOWNERDEAD

然后该线程负责清除任何不一致的状态。如果可以恢复,则该线程应在 pthread_mutex_unlock(3) 之前的任何时间调用 pthread_mutex_consistent(3),以便其他线程可以像以前一样使用它。如果无法恢复,则应在不调用 pthread_mutex_consistent(3) 的情况下解锁互斥体,使其进入不可用状态,唯一允许的操作是销毁它。

请注意,即使 EOWNERDEAD 被返回,互斥量也会被锁定(我认为这是 pthread_mutex_lock(3) 返回错误但锁定互斥量的唯一条件) .

要设置ROBUST 属性,请在初始化互斥属性实例后使用pthread_mutexattr_setrobust(3)。请记住,这必须在初始化互斥量之前完成。所以,像这样:

pthread_mutex_t mutex;
pthread_mutexattr_t mutex_attrs;

if (pthread_mutexattr_init(&mutex_attrs) != 0) {
/* Handle error... */
}
if (pthread_mutexattr_setrobust(&mutex_attrs, PTHREAD_MUTEX_ROBUST) != 0) {
/* Handle error... */
}
if (pthread_mutex_init(&mutex, &mutex_attrs) != 0) {
/* Handle error... */
}

然后你可以像这样使用它:

int lock_res = pthread_mutex_lock(&mutex);

if (lock_res == EOWNERDEAD) {
/* Someone died before unlocking the mutex
* We assume there's no cleanup to do
*/
if (pthread_mutex_consistent(&mutex) != 0) {
/* Handle error... */
}
} else if (lock_res != 0) {
/* Some other error, handle it here */
}

/* mutex is locked here, do stuff... */

if (pthread_mutex_unlock(&mutex) != 0) {
/* Handle error */
}

有关更多信息,您可以查看 pthread_mutex_consistent(3) 的联机帮助页和 pthread_mutex_getrobust(3) / pthread_mutex_setrobust(3)

关于linux - 如何在 Linux 中摆脱死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31638790/

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