Atomic memory access

来源:互联网 发布:黑谍淘宝宝贝复制专家 编辑:程序博客网 时间:2024/06/06 16:26

Gcc 提供了一些built in的函数,以实现内存访问的原子性:具体函数在http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html

In most cases, these builtins are considered afull barrier. That is, no memory operand will be moved across the operation, either forward or backward. Further, instructions will be issued as necessary to prevent the processor from speculating loads across the operation and from queuing stores after the operation. 

full barrier 就是说明了这些函数是通过cpu以memory barrier方式访问内存的,所以即使在多核CPU下,这些函数也可保证其原子性. 

也就隐含的说明了,不管是单进程还是多进程只要是对函数中ptr参数的内存地址的访问,都是原子进行的——如ptr是在共享内存中,那多个进程对ptr所指向的内存的访问都是原子进行的,保证了在多个进程间的同步,即使在多核cpu下.

Memory barrier: http://en.wikipedia.org/wiki/Memory_barrier