You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

持有已锁定健壮互斥锁的共享内存执行munmap后引发死锁的原因探究

Why does munmap before exiting cause pthread_mutex_lock to hang with robust mutex?

Great question—this behavior boils down to how the Linux kernel tracks robust mutexes and interacts with memory mappings. Let’s break down exactly what’s happening here:

Root Cause

When you use a robust mutex (PTHREAD_MUTEX_ROBUST), the kernel maintains a link between the mutex and the process holding it. If that process exits without unlocking the mutex, the kernel marks the mutex with the EOWNERDEAD state, letting subsequent processes detect the dead owner and recover the lock safely.

But when Process 1 calls munmap(shared, sizeof(shared_data_t)) before _exit(1), you’re breaking that critical link:

  • The kernel disassociates the shared memory region from Process 1’s address space.
  • Without that association, the kernel can’t confirm the mutex was held by Process 1 at exit time.
  • It doesn’t set the EOWNERDEAD flag on the mutex, so when Process 2 tries to lock it, the kernel thinks the lock is still held by a live process (even though Process 1 is gone) and blocks indefinitely waiting for a release that will never happen.

Official Documentation Reference

This edge case is explicitly covered in the pthread_mutexattr_setrobust(3) man page. The notes section states:

If a process holding a robust mutex terminates without unlocking the mutex, the mutex becomes inconsistent unless the process has already unmapped the memory containing the mutex. In the latter case, the mutex state is undefined, and subsequent operations on the mutex may behave unpredictably (e.g., block forever).

In short: Unmapping shared memory with a held robust mutex before exit leaves the mutex in an undefined state— the kernel can’t clean up the lock’s ownership metadata, so other processes can’t properly recover or even detect the dead lock owner.

Fixes & Best Practices

To avoid this hanging behavior:

  • Never unmap shared memory while holding a robust mutex: Always unlock the mutex first before calling munmap.
  • For crash simulation (like your test), skip the munmap call entirely. Let _exit(1) terminate the process without unmapping, so the kernel can correctly mark the mutex as EOWNERDEAD.

内容的提问来源于stack exchange,提问作者toxic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:49:07