Peter Dimov wrote:
Ben Hutchings wrote:
Paul wrote:
Synchronous cancellation may be simulated by setting a simple flag polled by the cancellable thread. (Appropriate memory barriers must be placed after setting and before polling the flag. In the absence of portable memory barrier facilities, one may protect the flag with a mutex, though that's annoyingly heavyweight.) However this does not
just out of curiousity, why do you think you need a memory barrier on a flag? you would have 1 writer and 1 reader... either the reader reads false or true, and once the writer has set it to true... thats it, the reader will read true on the next pass.
In practice, if you use "volatile" then the compiler will probably generate code to read the flag from memory every time and the reader will probably see the change, possibly after some small delay for it to work its way through the write queue on the processor that the writer is running on. AFAIK no standard or specification guarantees this.
If the cache of the reader CPU isn't notified about the change (which is only guaranteed to happen on an acquire) the reader may never observe the modified value.
I agree that there's no such guarantee, which is why I wouldn't advocate depending on this working. However, without a cache coherency protocol, independent shared variables cannot share a cache line and synchronisation is absurdly slow, and I'm not aware of any multiprocessor systems supporting general multithreading that don't have such a protocol. Write queues are of finite length and are eagerly flushed to cache to avoid stalling later memory-writing instructions where possible. Ben.