开发者

A mutex can only be released from the same thread that waited on it?

Is it true that a mutex can only be released from the thread that wait on that mutex开发者_如何学Python? If yes why the mutex behaves like this? So why we say a mutex can work across multiple processes? What is named-mutex and unnamed-mutex? I'm really confused about this issue!

If I want to wait on mutex in a thread and signal it from another thread, what should I do?


A mutual exclusion semaphore does have to be released by the same thread that obtained it. That's the way they work: a single thread acquires the lock on a resource so it can manipulate it and then, when it's finished, it releases that lock so that other threads may lock it.

The whole point of the "mutual exclusion" bit is that the thread with the lock has total power - only it can release that lock. That still allows the mutex to work across multiple threads because it can be owned by any one of them across its lifetime.

A named mutex allows a single mutex to also work across processes as well as threads. The name is used to allow a separate process to "connect" to an already-created mutex and it can then be used to control access to a resource across all connected processes.

For cross-thread communication like you desire, you're looking at something like a condition variable, which is used to signal threads that a condition has been met - I think the equivalent in .Net is the Monitor, with its Wait and Pulse methods.


A mutex has ownership - see paxdiablo post. If you want to wait on something in a thread and signal it from another thread, don't use a mutex! Event - OK, condvar-OK, monitor-OK, semaphore-OK, Event-OK, mutex-not OK.

Rgds, Martin


You cannot signal a mutex (= Mut-ual Ex-clusion kernel synchronization construct) from any other thread than the one who acquired it.


the short answer is that when the mutex is released (from the owning thread) the other threads will be notified

i.e. all threads doing wait on the mutex will compete over ownership of the mutex and the winner will return from the wait call and continue execution, in ownership of the mutex.

That being the difference of using a mutex from having to coordinate the signals yourself. Did that answer you question or have I misunderstood you?

BR Daniel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜