简体   繁体   中英

What does __sync_synchronize do?

I saw an answer to a question regarding timing which used __sync_synchronize().

  • What does this function do?
  • And when is it necessary to be used?

It is a atomic builtin for full memory barrier .

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.

Check details on the link above.

我猜它会强制使用内存栅栏

This builtin issues a full memory barrier.

For memory barrier, cpu sorts our instructions, which will improve efficiency generally, but it may cause unexpected results. For example, there may be four registers in the hardware: when you issue an operation command, one register saves your operation instruction (such as read), two registers save parameters (such as address, size), and the last register is a control register. After all parameters are ready, hardware will read parameters and execute the program, which could look like this:

    writereg (dev.register_size,size);
    writereg (dev.register_addr,addr);
    writereg (dev.register_cmd,READ);
    writereg (dev.register_control,GO);

If the last operation code is placed before the others, then that isn't what we expected, so we can put a memory barrier between the first three codes and the last one, to force the CPU to operate the last code after the first three codes:

    writereg (dev.register_size,size);
    writereg (dev.register_addr,addr);
    writereg (dev.register_cmd,READ);
    __sync_synchronize();
    writereg (dev.register_control,GO);

It stops queueing writes and caching reads.

"volatile" is compiler option to use code to immediately fetch or store a value, but modern CPUs also have multiple cores with memory caches and delayed writes to external memory. __sync_synchronize() makes sure all cores see the same values at the same time.

...
X = new_value; // compiler and/or CPU could update X later when convienent
...
if ( X ) ... // compiler and/or CPU could use previous cached value of X
...

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