简体   繁体   中英

What are examples of memory barriers in C++?

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?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM