Superpolock
Superpolock

Reputation: 3615

What does __sync_synchronize do?

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

Upvotes: 37

Views: 47882

Answers (4)

Codemeister
Codemeister

Reputation: 117

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
...

Upvotes: 0

RecharBao
RecharBao

Reputation: 371

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

Upvotes: 4

nik
nik

Reputation: 13450

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.

Upvotes: 44

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

It forces a memory fence I guess.

Upvotes: 6

Related Questions