Synchronization Tools
Atomic
operations – Atomic operations are a simple form of
synchronization that work on simple data types. The advantage of atomic
operations is that they do not block competing threads. For simple operations
such as incrementing a counter variable, this can lead to much better
performance than taking a lock.
Memory
Barriers a volatile variables – In order to achieve optimal
performance, compilers often reorder assembly-level instructions to keep the
instruction pipeline for the processor as full as possible. A memory barrier is
a type of nonblocking synchronization tool used to ensure that memory
operations occur in the correct order.
Locks – Locks are one of the most commonly used
synchronized tools. You can use locks to protect a critical section of your
code, which is a segment of code that only one thread at a time is allowed
access. For eg. a critical section. If one thread is synchronized on an object,
and a second thread tries to synchronize on the same object, the second thread
is forced to wait until the first thread has finished with the object. This is
implemented using lock. Every object has a lock, and that lock can be ‘held’
only by one thread at a time. To enter a synchronized statement a thread must
obtain the associated object lock. if thread A tries to obtain a lock that is
already held by thread B, then thread A has to wait until thread B release the
lock. In fact, thread A will go to sleep, and will not be awoken until the lock
becomes available.
Comments
Post a Comment