c 中Monitor的使用

2022-06-11 22:06:14 字數 1021 閱讀 7282

首先lock和minitor有什麼區別呢?

其實lock在il**中會被翻譯成monitor。也就是monitor.enter(obj)和monitor.exit(obj).

lock(obj)

等價為:

trycatch()

{}finally

所以lock能做的,monitor肯定能做,monitor能做的,lock不一定能做。那麼monitor額外的功能呢?

1:monitor.tryenter(obj,timespan)----timeout之後,就不執行這段**了。lock可是一直會死等的。

2:還有monitor.wait()和monitor.pulse()。在lock**裡面如果呼叫了monitor.wait(),會放棄對資源的所有權,讓別的執行緒lock進來。然後別的執行緒**裡pulse一下(讓原執行緒進入到等待佇列),然後在wait一下釋放資源,這樣原執行緒的就可以繼續執行了(**還堵塞在wait那句話呢)。

也就是說,必須兩個或多個執行緒共同呼叫wait和pulse,把資源的所有權拋來拋去,才不會死鎖。

和autoevent相似是處理同步關係的,但是autoevent是跨程序的,而monitor是針對執行緒的。

以下是msdn的**示例,除錯起來很容易看出來兩個函式的作用了,因為儘管是多執行緒程式,但是是同步操作,所以**始終是單步執行的。

using system;

using system.threading;

using system.collections;

namespace monitorcs1

public void firstthread()

int i = 0;}}

public void secondthread()}}

//return the number of queue elements.

public int getqueuecount()

static void main(string args)}}

c 中Monitor的使用

首先lock和minitor有什麼區別呢?其實lock在il 中會被翻譯成monitor。也就是monitor.enter obj 和monitor.exit obj lock obj 等價為 try catch finally 所以lock能做的,monitor肯定能做,monitor能做的,lo...

c 中Monitor的使用

首先lock和minitor有什麼區別呢?其實lock在il 中會被翻譯成monitor。也就是monitor.enter obj 和monitor.exit obj lock obj 等價為 trycatch finally 所以lock能做的,monitor肯定能做,monitor能做的,loc...

C 中使用Monitor鎖定臨界物件

using system using system.collections.generic using system.text using system.threading namespace monitertest console.writeline worker1 worker1count.to...