> Here is an example scenario where this property is useful: > \- write into a > container on thread 1 (only append/add data e.g. I/O loop) > \- iterate > (read) over the container in thread 2 (e.g. UI thread)
Use threadsafe containers or locks. You have a race condition here where if an item is enqueue, thread 2 can read uninitialized memory, then thread 1 initializes the memory. > How would the compiler re-order the read here ? If self.len is read each > iteration, i.e. increases mid-iteration (which you could avoid via a temp > var), you'll be guaranteed to not read invalid memory in this scenario. Any compiler will only read the length once and store it in register instead of paying for N memory access. It's a basic optimization.