对 pthread 互斥体所涉及的完整内存屏障的说明屏障、所涉及、内存、完整

2023-09-08 09:45:38 作者:更精彩的活∫

我听说在处理互斥体时,必要的内存屏障由 pthread API 本身处理.我想了解有关此事的更多详细信息.

至少在最常见的架构上,这些说法是否属实?编译器是否识别此隐式屏障,并在生成代码时避免重新排序操作/从本地寄存器读取?什么时候应用内存屏障:成功获取互斥锁后和释放后?

解决方案 Windows事件等待学习笔记 四 事件 信号量 互斥体

POSIX 规范列出了必须"与其他线程同步内存",包括pthread_mutex_lock()pthread_mutex_unlock()等函数.p>

在 附录 A.4.11 中明确指出同步内存"的函数:

...必须被高级编译系统识别,以便内存操作和对这些函数的调用不会被优化重新排序;和

...可能必须添加内存同步指令,具体取决于特定的机器.

从来没有明确指定隐含什么样的内存同步指令——隐含的规范是,如果你使用一对同步指令"来确保一个线程中的读取必须发生在另一个线程中的写入之后,那么您的程序将正常运行.这包括编译器和架构重新排序效果.

I have heard that when dealing with mutexes, the necessary memory barriers are handled by the pthread API itself. I would like to have more details on this matter.

Are these claimings true, at least on the most common architectures around? Does the compiler recognize this implicit barrier, and avoids reordering of operations/read from local registers when generating the code? When is the memory barrier applied: after successfully acquiring a mutex AND after releasing it?

解决方案

The POSIX specification lists the functions that must "synchronize memory with respect to other threads", which includes functions like pthread_mutex_lock() and pthread_mutex_unlock().

In Appendix A.4.11 it is spelt out that functions that "synchronize memory":

...would have to be recognized by advanced compilation systems so that memory operations and calls to these functions are not reordered by optimization; and

...would potentially have to have memory synchronization instructions added, depending on the particular machine.

It is never explicitly specified what kind of memory synchronization instructions are implied - the implicit specification is that if you use a pair of "synchronizing instructions" to ensure that a read in one thread must happen after a write in the other, then your program will operate correctly. This includes both compiler and architectural reordering effects.