Question

Imagine a scenario: 2 cores what to do CaS at the same exact same time. A processor needs to read an old value, THEN place a new one, IN the old one is the same. What if they read simultaneously? Or is there any sort of lock put on the variable there, preventing other cores from reading?

Was it helpful?

Solution

Yes, on most architectures each core would attempt a Read-For-Ownership flow, which means it asks for the line exclusively with the purpose of changing it. One of them would win, sending the data back to the requesting core and making the other request block or recycle somehow. The exact details depend on the design, but in general you could expect the winning core to consume the data and change it to the new value atomically (through internal locking, so it can't be interfered in the process), and then finish the operation with the new data either written back or cached internally (in modified state).

At that point the other request may continue and attempt to get ownership on the line - if this line is still held in the first core, that would result in a snoop reading the modified data. Then the second core can repeat the same process as the first one.

On simpler systems the same can be achieved by stopping all memory transactions during this process (a "bus lock", like Egor mentioned), but that's pretty rare these days as the performance is horrible, so it's kept for really complicated cases like when the variable isn't aligned and the data splits between two lines.

Note that the crucial part (the CaS), should ideally be done internally within the core, where the local cache line lock can maintain atomicity (no one else can read or take ownership on that line while he's locking it), while other cores can access other memory addresses without loss of coherency or atomicity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top