Asynchronous and parallel ~ ReaderWriterLockSlim implements the shared lock and mutex lock, readerwriterlockslim
Returned directory
In System. threading. in the Tasks namespace, The ReaderWriterLockSlim object is used to implement lock management when multiple threads are concurrent. It provides better performance and reasonable performance than lock. We all know that lock can lock code blocks, when multiple threads access code together, only one thread can access it, and other threads are blocked. This is required for write operations, but it is a waste of resources for read operations, because our read operations should be shared, multiple threads can read it now, which leads to the ReaderWriterLockSlim object, which is used to implement the shared lock and mutex lock!
Declare a read/write lock
private static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
EnterReadLock and ExitReadLock-shared lock
When a thread uses a shared lock, other threads can access this resource and share this lock object.
RwLock. enterReadLock (); Console. writeLine (DateTime. now. toLongTimeString () + "Thread {0} Read data", Thread. currentThread. managedThreadId); Thread. sleep (10000); rwLock. exitReadLock ();
EnterWriteLock and ExitWriteLock-mutex lock
When a thread uses a mutex lock, other threads will be blocked until the thread releases the lock (ExitWriteLock ).
RwLock. enterWriteLock (); Console. writeLine (DateTime. now. toLongTimeString () + "Thread {0} written data {1}", Thread. currentThread. managedThreadId, res); Thread. sleep (10000); rwLock. exitWriteLock ();
During the test, we can use multiple concurrent threads to call the same locking code and check the execution time.
// Multi-threaded Parallel. invoke () =>{ TestReadWrite ("1") ;}, () =>{ TestReadWrite ("2 ");},() =>{ TestReadWrite ("3 ");});
Execution result
We can see that when the shared lock is accessed, several threads are at the same time; while the mutex lock is in use, there is a waiting (blocking) between threads )!
Thank you for reading this article!
Returned directory