Some time ago carefully read some of the information on multithreading, the project used to thread the place is also a lot of, but, when read a Jeffrey of the article on the lock, found himself although the use of multiple threads, but the lack of multithreaded programming needs to think! So I want to start with Jeffrey's Optex (lock) to talk about what I have learned from it.
In. NET, the most locking mechanism we use is lock, which is simple to use and can be implemented in just a few lines, such as:
Lock ' s Code
public class TestThreading
{
private System.Object lockThis = new System.Object();
public void Function()
{
lock (lockThis)
{
// Access thread-sensitive resources.
}
}
}
In fact, we also understand that lock is not a lock, but Ms provides a simple style of writing, the real implementation of the Monitor class in the Enter and exit methods, since the mention of the Monitor class also said there is a need to pay attention to the place:
Pulse and PulseAll methods, the two methods are to notify the thread in the waiting queue of the message that the lock state will change, but if there is no thread in the waiting queue, the method waits until there is a waiting thread entering the queue, which means that the method may cause a class of test deadlocks to occur.
Top lock + thread (thread and ThreadPool) = multithreaded programming (N%)!?
For the formula I used to have n is 80, now is 20. There are many things that affect me, let me from 80->20, the following Optex is an entry point.
Optex ' s Code
public sealed class Optex:idisposable {
Private Int32 m_waiters = 0;
Private semaphore M_waiterlock = new Semaphore (0, Int32.MaxValue);
Public Optex () {}
public void Dispose () {
if (m_waiterlock!= null)
{
M_waiterlock.close ();
M_waiterlock = null;
}
}
public void Enter () {
thread.begincriticalregion ();
ADD ourself to the set of threads interested in the Optex
if (interlocked.increment (ref m_waiters) = 1) {
//If We were the the ' the ' the ' the ' the ' the ' the ' the ' the ' the ' the '
return;
}
//Another thread has the Optex, we need to wait for it
M_waiterlock.waitone ();
When WaitOne returns, this thread now has the Optex
}
public void Exit () {
//SUBTR Act ourself from the set of threads interested in the Optex
if Interlocked.decrement (Ref M_waiters) > 0 {
//Other threads are waiting, wake 1 of them
M_waiterlock.release (1); }
Thread.EndCriticalRegion ();
}
}