- We can share data bet. multiple threads.
- multithreading - multiple thredas might be interrogating our objs simult.
- Interlocked.Increment - adds 1 to value as atomic operation.
- Interlocked Class - only works with small number of .NET types.
Syncronization Locks
- Synch locks - to allow one to synch. access to objects in .NET. Can synch access to your own classes + treat larger sections of code as atomic.
- deadlocks - be careful!!
Other Synch. Mthds.
- ReaderWriterLock class - lock access to readers and writers separately - allow mult. concurrent readers but only a sinlge writer.
- To acquire a reader lock:
- 1) Instance of ReaderWriterLock class - to be shared across any threads.
- 2) try/catch block - catch ApplicationException - where acquisition of reader lock fails.
- 3) acquire lock - ReaderWriterLock.AcquireReaderLock.
- 4) try/finally - to hold any read code. thread-safe read in try, release lock in finally.
- To acquire a wrtier lock - analogous.
- Windows kernel objs - Mutex, Semaphore, Event.
- Much slower than using Monitor.
- When to use?:
- 1) Mutex - allows synch. across AppDomain and process boudaries.
- 2) Semaphore - throttles access to a resource to a set no. of threads.
- 3) Event - provides a way to notify mult. threads - across AppDomain and process boundaries - that some event has occurred.
- Mutex
- 1) create instance of Mutex to be shared across any threads - Mutex m = new Mutex();
- 2) WiatOne - to wait until lock is available.
- 3) try/finally - try - do thread-safe work - finally - release lock.
No comments:
Post a Comment