- There are three operations usually involved with arithmetic operations on variables, i.e. Load Variable value into Register, Change value in Register, Write Back the new value to variable.
- In threaded code, all the above steps/operations are treated as atomic operations.
- Therefore, it might happen that two threads read/load the same variable into the register, change its value equally and write it back, all at the same time. (Valid in multi-core or multi-processor scenario)
- Interlocked class may be used to accertain that a certain variable is accessed by only one thread in a multi-threaded application.
- Interlocked class has static methods which can be used when performing arithmetic operations on variables.
- However, interlocked class has some limitations. It cannot be used for a wide variety of types and cannot be used to make pieces of code thread-safe. (Refer to Page 392)
- To declare a piece of code as thread-safe, use lock keyword to create thread-safe block. Lock keyword requires and object reference passed to it (usually this).
- This creation of lock block is called Synchronization Locks.
- Synchronization Locks may also be created using Monitor class static methods.
- To avoid deadlocks, we may use Monitor.TryEnter( ) method. Otherwise use Timeout.Infinite static property to tell the thread to wait as long as it takes.
- If we wish to deal (synchronize) reading and writing operations seperately, we may use ReaderWriterLock class to lock certain data only for reading or writing.
- LockCookie type object would be required to downgrade a WriterLock to a ReaderLock. (This implies that a WriterLock is downgradable only if it was previously upgraded from a ReaderLock)
- Three OS kernel level objects are represented in .NET by classes named Mutex, Semaphore, AutoResetEvent and ManualResetEvent. All of these derive from WaitHandle class.
- Mutex is almost same as Monitor class with the fact that it allows synchronization across AppDomain and process boundaries.
Showing posts with label Lock. Show all posts
Showing posts with label Lock. Show all posts
Tuesday, July 14, 2009
Chapter 7-Lesson 2
Labels:
Interlocking,
Lock,
Synchronization,
Thread,
Thread Safety
Subscribe to:
Posts (Atom)