对 pthread 互斥体所涉及的完整内存屏障的说明 [英] clarifications on full memory barriers involved by pthread mutexes

查看:33
本文介绍了对 pthread 互斥体所涉及的完整内存屏障的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

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.

  1. Are these claimings true, at least on the most common architectures around?
  2. Does the compiler recognize this implicit barrier, and avoids reordering of operations/read from local registers when generating the code?
  3. 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.

这篇关于对 pthread 互斥体所涉及的完整内存屏障的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆