c - pthread_atfork 锁定习语坏了?

标签 c pthreads posix fork

pthread_atfork 用法的标准用法应该是获取预 fork 处理程序中的所有锁,并在父处理程序和子处理程序中释放它们。但是据我所知,这是不可能的。 pthread_mutex_unlock 如果调用线程不是互斥体。并且在用 pthread_atfork 注册的子处理程序中,调用线程是新创建进程的主线程,因此不能互斥量的所有者。

是我弄错了还是整个 pthread_atfork 习惯用法被设计破坏并且基本上无法使用?

编辑:我也没有看到针对该问题的任何有效(可移植)解决方法。理想情况下,我们可以销毁并重新初始化子进程中的互斥体,除了在初始化的互斥体上调用 pthread_mutex_destroy 被指定为未定义的行为,以适应互斥体不是 POD 但涉及一个可笑的实现对某些内核级对象的引用。

最佳答案

我认为这是来自 man 的相关文本:

When fork() is called, only the calling thread is duplicated in the child process. Synchronization variables remain in the same state in the child as they were in the parent at the time fork() was called. Thus, for example, mutex locks may be held by threads that no longer exist in the child process, and any associated states may be inconsistent. The parent process may avoid this by explicit code that acquires and releases locks critical to the child via pthread_atfork(). In addition, any critical threads need to be recreated and reinitialized to the proper state in the child (also via pthread_atfork()).

在子进程中执行 atfork 处理程序的线程是在父进程中执行 atfork 准备处理程序的线程的精确副本,因此有权解锁互斥量。

关于c - pthread_atfork 锁定习语坏了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5473368/

相关文章:

c - 有没有办法到管道的最后位置而不是读取直到什么都没有?

c++ - vector 异常处理程序和 Microsoft C 运行时错误处理

我可以让 Unix 的 pthread.h 在 Windows 中编译吗?

c - 是否有安全的方法来检查 pthread 是否存在?

c - gdb 没有正确打印字符串值

c++ - 仅列出目录中的文件夹

c++ - wcsdup 分配的内存是否应该显式释放?

c - typedef A (*AF)() 是什么意思?

c++ - unsigned Char 循环将运行多少次

c - 程序输出 2^n 而不是预期的