|
TO: lock only guarantees that there will not be multiple threads writing to a certain code at the same time
But there is no guarantee that only one thread will read the same code
This happens because:
public static void Run ()
{
lock (thisLock)
{
while (lNum <100)
{
lNum ++;
Console.WriteLine ("Thread {0}: lNum = {1}", Thread.CurrentThread.Name, lNum);
}
}
The while loop is in the lock.For example, thread 1 gets the mutex of the thread, then other threads cannot access the code inside:
while (lNum <100)
{}
So after thread 1 gets the mutex, it runs the while loop, and it will not release the mutex until the loop reaches 100. When other threads get the mutex, the runtime finds that lNum is already 100, so they all quit.
And if:
while (count <= 100)
{
mx.WaitOne ();
count ++;
Debug.WriteLine ("thread" + Thread.CurrentThread.Name + ":" + count.ToString ());
Thread.Sleep (100);
mx.ReleaseMutex ();
}
That is, the while loop is outside, the effect is not the same, it gets the mutex right inside the loop, gets the mutex right before incrementing 1, and releases the mutex right after incrementing 1, so each thread will have the opportunity to increase the variable by 1. .. |
|