spring/spring — comment on commit e6bfced1b2e5a699cfe65ee0af40ce42d9b2be29
File:  line 0
By jk3064:

Okay here a small essay. First the 4 situations that may happen:

__sim-thread reads/writes + worker-thread readswrites__
Two objects will have the same id, still only one synced object is under them
-> everything is fine

__sim-thread writes + worker-thread reads__
can be ingored (unsynced objects don't need a changing sync_id at all)
-> everything fine

__sim-thread reads + worker-thread writes__
i) In the case the change only affects the lower 32bit of the value
-> everything is fine
ii) In the case it affects the upper 32bit it may break. When the upper 32bit was updated but the lower wasn't, then the sim-thread reads a value that is 2^32 too large. Still this only affects only each 2^32 update, and could be solved via an if-branch + atomic write.
-> happens rarely

__worker-thread read a value & stalls then (waiting for cache, OS scheduler etc.) while sim-thread uses that time to create multiple objects__
worker-thread read number _x_, while sim-thread created _n_ objects, so memory location will contain the value _x+n_. Now shortly after that the work-thread begins to work again and writes its old value _x_ to the memory
-> breaks, can't be solved via an atomic write (there would still be a delay between read & write), solutions are more extended atomic ops like fetch&add or compare&swap

@ int64 atomic ops on 32bit-arch
There are atomics for this even on 32bit, either by GCC itself via builtins (I assume they emulate them) or as CPU cmdops. So the CPU has cmpxchg8b to compare&swap a int64, also the 80bit FPU can be used to write atomic an int64 (http://www.niallryan.com/node/137). But we need the first (read&write must be atomic).

So I did a few performance tests and it showed that cmpxchg8b is only 2.5x slower than non-locked increase & GCC builtins (i.e. __sync_fetch_and_add) are like 5x slower. Results + source are here: http://pastebin.com/eXTSEBk4