Reputation: 9809
Can memory barriers be achieved through code(without using CAS or other locking primitives like volatile,atomic classes etc.)?
I believe the disruptor is able to achieve it,without actually ersorting to any of the locking primitives.
Any pointers or references in understanding this would be helpful.
Suggestions on other programmatic modes(preferrably in java) is also appreciated.
Upvotes: 1
Views: 310
Reputation: 4049
The notion of a memory barrier is orthogonal to CAS and other locking primitives. For example, C++11 allows a CAS operation to not have any memory barrier at all if specified with memory_order_relaxed. Some hardware, notably x68, always associates a memory barrier with an atomic read-modify-write operation.
The best example of an algorithm that requires a memory barrier, but no CAS or locking, is Dekker's protocol. Section 1 of "Location-Based Memory Fences" gives a good overview of the protocol.
See my blog Volatile: Almost Useless for Multi-Threaded Programming for why volatile is useless as a memory barrier.
C++-specific information: In C++11, use std::atomic_thread_fence. The preceding link has a nice example of using it without locking. If dealing with older C++ compilers, you'll need to resort to vendor-specific routines. One way is to use Intel Threading Building Blocks' tbb::atomic_fence(). It's a wrapper around whatever platform-specific fence we could find.
Upvotes: 1