Monitor vs Mutex

前端 未结 3 1947
感动是毒
感动是毒 2021-01-30 21:08

I read that mutex is a semaphore with value 1 (binary semaphore) used to enforce mutual exclusion.

I read this link Semaphore vs. Monitors - what's the difference? wh

3条回答
  •  既然无缘
    2021-01-30 21:23

    Unfortunately the textbook definitions does not always correspond to how different platforms and languages use the terms. So to get precise answers you have to specify the platform and context. But in general:

    A mutex is a lock which can only be owned by a single thread at a time. The lock doesn't in itself protect anything, but code can check for ownership of a mutex to ensure that some section of code is only executed by a single thread at a time. If a thread wants to acquire a mutex lock the thread is blocked until it becomes available.

    In Java terminology a monitor is a mutex lock which is implicitly associated with an object. When the synchronized keyword is applied to classes or methods an implicit mutex lock is created around the code, which ensures that only one thread at a time can execute it. This is called a monitor lock or just a monitor.

    So in Java a monitor is not a specific object, rather any object has a monitor lock available which is invoked with the synchronized keyword.

    The synchronized keyword can also be used on a block of code, in which case the object to lock on is explicit specified. Here it gets a bit weird because you can use the monitor of one object to lock access to another object.

    In computer science textbooks you may meet a different kind of monitor, the Brinch-Hansen or Hoare-monitor, which is a class or module which is implicitly thread-safe (like a synchronized class in Java) and which have multiple conditions threads can wait/signal on. This is a higher-level concept than the Java monitor.

    C#/.net has monitors similar to Java, but also have a Mutex class in the standard library - which is different from the mutex lock used in the monitor. The monitor lock only exist inside a single process, while the Mutex-lock is machine wide. So a monitor lock is appropriate for making objects and data-structures thread safe, but not for providing system-wide exclusive access to say a file or device.

    So bottom line: These terms can mean different things, so if you want a more specific answer you should specify a specific platform.

提交回复
热议问题