2019年3月4日 星期一

C# 執行緒(Thread)的Mointer探討

Mointer跟Lock一樣,具有「鎖」的功用,用來確保在critical section中只有一個執行緒能夠執行,使用Monitor.Enter()進入鎖定,Monitor.Exit() 退出鎖定,他其實就是Lock機制的應用:

bool lockWasTaken = false;
var temp = obj;
try
{
    Monitor.Enter(temp, ref lockWasTaken);
    { body }
}
finally
{
    if (lockWasTaken) Monitor.Exit(temp);
}

另外他還提供了其他方法以供運用:
  • Monitor.Enter() : Acquires an exclusive lock on the specified object. This action also marks the beginning of a critical section.
  • Monitor.Exit() : Releases an exclusive lock on the specified object. This action also marks the end of a critical section protected by the locked object.
  • Monitor.Pules() : Notifies a thread in the waiting queue of a change in the locked object's state.
  • Monitor.Wait() : Releases the lock on an object and blocks the current thread until it reacquires the lock.
  • Monitor.PulesAll() : Notifies all waiting threads of a change in the object's state.
  • Monitor.TryEnter() : Attempts to acquire an exclusive lock on the specified object.

沒有留言:

張貼留言