0

if two different cores try to write to the same spot in main memory at the same time, what happens? Does main memory automatically only allow a spot in memory to be written one-at-a-time, or does some kind of expensive locking have to occur?

(Basically I want to know how expensive writing to an atomic volatile int is, and if it has affects on other processes & threads that don't access it, e.g. if the bus got locked it would affect everything, right?)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Mohamed Hafez
  • 8,621
  • 7
  • 41
  • 49

2 Answers2

1

Every multi core CPU has a means to ensure that each core's write is sequenced on a first come first served basis. If it didn't you'd have a situation where the two cores were both trying to drive the memory bus at the same time, and that will cause smoke to be emitted.

So yes, locking does occur at the electronic level, but it's not expensive. It is relatively complex though because the memory is reflected in cache, so a mechanism called bus snooping allows a cache to spot when another core or peripheral changes the contents of a memory location that it is currently caching.

So if no other process or core is using the same memory location then their caches won't be caching it so your read write will take place unhindered. Initially the write will only be to cache, and it will only be written to main memory if the running processes access enough memory elsewhere to oblige the cache to flush.

bazza
  • 7,580
  • 15
  • 22
  • Your conclusion is right for the wrong reasons. Bus *locking* doesn't happen. You don't have multiple writers connected to the same physical memory bus anyway; you have one controller per channel, with multiple DIMMs. Arbitration between cores happens when they ask for exclusive ownership of the cache line. [MESI](https://en.wikipedia.org/wiki/MESI_protocol) is often shown in terms of an *actual* shared bus, but that's ancient history. Instead we have memory controllers attached to each socket of a multi-socket system, with an interconnect between cores. – Peter Cordes Feb 11 '22 at 00:49
  • See [What happens when different CPU cores write to the same RAM address without synchronization?](https://stackoverflow.com/q/48817022) – Peter Cordes Feb 11 '22 at 00:50
0

The hardware only has one physical connection to memory. It cannot be written to by two different sources at the same instant. It can appear to happen though.

If you try to do a read, then write, from two processes/threads then if they overlap it can cause this. The 'mutex', which atomic operations are used for, implements a way to get around it.

Jay
  • 13,803
  • 4
  • 42
  • 69