In this case, there are two threads are "modifying each other's data", which indeed would require the compiler to KNOW that the data is being modified by another thread. There are several solutions to solve this, volatile
will tell the compiler that it can't store the value in a register from the first read, but there are problems with that....
Most importanly, volatile
will NOT solve the problem of precisely detecting the "edge" when the d[1] > 0
is being changed, since with volatile
, all you are guaranteed is that the compiler doesn't remove the read of the variable. In a system with multiple cores, there could well be a "delay" between the new data in thread 1 reaching thread 2. Meaning that d[0]
may be modified more times than you expected, because the loop ran a few extra cycles. In extreme cases, such as certain models of ARM processors, the loop may run more or less indefinitely since the processor(core) will need the cache-line flushed, and that will not happen without intervention unless something else is using that same cache-line. In a system that is otherwise not busy, this may take as long as you've got, or longer... ;)
So, I don't agree that volatile
isn't needed in multithreaded environments, but I do agree that it's not the whole solution. The std::atomic
and other similar constructs are required to ensure the correctness if detecting values has changed "immediately" is needed for the code to work correctly.
Sharing data across threads is a difficult matter, and it needs careful planning and understanding to make it work right. I know the above code is probably just a simplified example, but if modify(d[1])
is trivial, then it would be a very bad case of sharing data, and it is likely that it will run MUCH slower as two threads than as single-threaded loop, because every cache-line write by one processor will force a flush of the cache-line on the other processor. So it will be like driving a Ferrari sports car in busy Manhattan traffic - not very energy efficient, and no faster than the simple solution.