What are examples of memory barriers in C++?

▼魔方 西西 提交于 2019-12-12 08:26:15

问题


I see C++11 mutexes lock is not void lock() volatile. How does the compiler know which functions are memory barriers and which are not? Are all functions barriers even if they are not volatile? What are some less known memory barriers and memory barriers everyone should know?


回答1:


The runtime library has to implement a mutex in a way so that the compiler knows! The language standard doesn't say anything about how to do this.

Likely, it involves a call to some operating system service that works as a memory barrier. Or the compiler can have an extension, like void _ReadWriteBarrier();




回答2:


The actual implementation of your std::mutex will be such that the compiler doesn't perform illegal reordering, doesn't elide variable loads, and it will ensure that the lock variable is accessed atomically and that the CPU performs the necessary memory barriers for lock acquisition and release.

The details of how much work needs to be done to ensure this vary from platform to platform, but your library implementation will Do The Right Thing.



来源:https://stackoverflow.com/questions/11709736/what-are-examples-of-memory-barriers-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!