What are the differences between Mutex vs Semaphore? When to use mutex and when to use semaphore?

Concrete understanding of Operating System concepts is required to design/develop smart applications. Our objective is to educate  the reader on these concepts and learn from other expert geeks.

As per operating system terminology, the mutex and semaphore are kernel resources that provide synchronization services (also called as synchronization primitives). Why do we need such synchronization primitives? Won’t be only one sufficient? To answer these questions, we need to understand few keywords. Please read the posts onatomicity and critical section. We will illustrate with examples to understand these concepts well, rather than following usual OS textual description.

The producer-consumer problem:

Note that the content is generalized explanation. Practical details will vary from implementation.

Consider the standard producer-consumer problem. Assume, we have a buffer of 4096 byte length. A producer thread will collect the data and writes it to the buffer. A consumer thread will process the collected data from the buffer. Objective is, both the threads should not run at the same time.

Using Mutex:

A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa.

At any point of time, only one thread can work with the entire buffer. The concept can be generalized using semaphore.

Using Semaphore:

A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.

Misconception:

There is an ambiguity between binary semaphore and mutex. We might have come across that a mutex is binary semaphore. But they are not! The purpose of mutex and semaphore are different. May be, due to similarity in their implementation a mutex would be referred as binary semaphore.

Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there will be ownership associated with mutex, and only the owner can release the lock (mutex).

Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend called you, an interrupt will be triggered upon which an interrupt service routine (ISR) will signal the call processing task to wakeup.

General Questions:

1. Can a thread acquire more than one lock (Mutex)?

Yes, it is possible that a thread will be in need of more than one resource, hence the locks. If any lock is not available the thread will wait (block) on the lock.

2. Can a mutex be locked more than once?

A mutex is a lock. Only one state (locked/unlocked) is associated with it. However, a recursive mutex can be locked more than once (POSIX complaint systems), in which a count is associated with it, yet retains only one state (locked/unlocked). The programmer must unlock the mutex as many number times as it was locked.

3. What will happen if a non-recursive mutex is locked more than once.

Deadlock. If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. It is because no other thread can unlock the mutex. An operating system implementer can exercise care in identifying the owner of mutex and return if it is already locked by same thread to prevent deadlocks.

4. Are binary semaphore and mutex same?

No. We will suggest to treat them separately, as it was explained signalling vs locking mechanisms. But a binary semaphore may experience the same critical issues (e.g. priority inversion) associated with mutex. We will cover these later article.

A programmer can prefer mutex rather than creating a semaphore with count 1.

5. What is a mutex and critical section?

Some operating systems use the same word critical section in the API. Usually a mutex is costly operation due to protection protocols associated with it. At last, the objective of mutex is atomic access. There are other ways to achieve atomic access like disabling interrupts which can be much faster but ruins responsiveness. The alternate API makes use of disabling interrupts.

6. What are events?

The semantics of mutex, semaphore, event, critical section, etc… are same. All are synchronization primitives. Based on their cost in using them they are different. We should consult the OS documentation for exact details.

7. Can we acquire mutex/semaphore in an Interrupt Service Routine?

An ISR will run asynchronously in the context of current running thread. It is not recommended to query (blocking call) the availability of synchronization primitives in an ISR. The ISR are meant be short, the call to mutex/semaphore may block the current running thread. However, an ISR can signal a semaphore or unlock a mutex.

8. What we mean by “thread blocking on mutex/semaphore” when they are not available?

Every synchronization primitive will have waiting list associated with it. When the resource is not available, the requesting thread will be moved from the running list of processor to the waiting list of the synchronization primitive. When the resource is available, the higher priority thread on the waiting list will get resource (more precisely, it depends on the scheduling policies).

9. Is it necessary that a thread must block always when resource is not available?

Not necessarily. If the design is sure ‘what has to be done when resource is not available‘, the thread can take up that work (a different code branch). To support application requirements the OS provides non-blocking API.

For example POSIX pthread_mutex_trylock() API. When the mutex is not available the function will return immediately where as the API pthread_mutex_lock() will block the thread till resource is available.

References:

http://www.netrino.com/node/202

http://doc.trolltech.com/4.7/qsemaphore.html

Also compare mutex/semaphores with Peterson’s algorithm and Dekker’s algorithm. A good reference is the Art of Concurrency book. Also explore reader locks and writer locks in Qt documentation.

Exercise:

Implement a program that prints a message “An instance is running” when executed more than once in the same session. For example, if we observe word application or Adobe reader in Windows, we can see only one instance in the task manager. How to implement it?

Article compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Mutex vs Semaphore的更多相关文章

  1. mutex与semaphore的区别

    网摘1:Mutex 的发音是 /mjuteks/ ,其含义为互斥(体),这个词是Mutual Exclude的缩写.Mutex在计算机中是互斥也就是排他持有的一种方式,和信号量-Semaphore有可 ...

  2. 内核必看: spinlock、 mutex 以及 semaphore

    linux 内核的几种锁介绍 http://wenku.baidu.com/link?url=RdvuOpN3RPiC5aY0fKi2Xqw2MyTnpZwZbE07JriN7raJ_L6Ss8Ru1 ...

  3. 线程同步 –Mutex和Semaphore

    上一篇介绍了同步事件EventWaitHandle,以及它的两个子类型AutoResetEvent和ManualResetEvent.下面接着介绍WaitHandle的另外两个子类型Mutex和Sem ...

  4. Mutex vs Semaphore vs Monitor vs SemaphoreSlim

    C#开发者(面试者)都会遇到Mutex,Semaphore,Monitor,SemaphoreSlim这四个与锁相关的C#类型,本文期望以最简洁明了的方式阐述四种对象的区别. 线程安全 教条式理解 如 ...

  5. multithread synchronization use mutex and semaphore

    #include <malloc.h> #include <pthread.h> #include <semaphore.h> struct job { /* Li ...

  6. 【转】深层次探讨mutex与semaphore之间的区别(下)

    原文网址:http://blog.chinaunix.net/uid-23769728-id-3173282.html 这篇博文很长,虽然这是下篇,但还没结束,benchmark方面的东西正在进行中, ...

  7. java开发中的Mutex vs Semaphore

    先看一下stackoverflow上是怎么说的吧 原文地址:http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore- ...

  8. 线程同步之mutex和Semaphore

    表示之前对semaphore信号量木有神码概念. 比较纳闷这玩意要干嘛,好吧继续stackflow: Mutex can be released only by thread that had acq ...

  9. 多线程同步与并发访问共享资源工具—Lock、Monitor、Mutex、Semaphore

    “线程同步”的含义   当一个进程启动了多个线程时,如果需要控制这些线程的推进顺序(比如A线程必须等待B和C线程执行完毕之后才能继续执行),则称这些线程需要进行“线程同步(thread synchro ...

随机推荐

  1. 8套迷人精致的CSS3 3D按钮动画

    1.纯CSS3 3D按钮 按钮酷似牛奶般剔透 CSS3按钮一般都可以设计的非常漂亮,利用投影.渐变等CSS3属性特效可以把按钮渲染的十分动感.今天分享的这款CSS3按钮外观非常特别,它看上去酷似晶莹剔 ...

  2. 《JavaScript高级程序设计》心得笔记-----第三篇章

    第十章 1.    DOM1级定义了一个Node接口,以Node类型实现(除IE以外),为了确保跨浏览器兼容,最好用nodeType属性与数字数值进行比较(someNode. nodeType==1) ...

  3. Centos6.4版本下搭建LAMP环境

    Centos6.4版本下搭建LAMP环境 配置yum mkdir/mnt/cdrom mount/dev/cdrom  /mnt/cdrom 装载光盘 vi /etc/yum.repos.d/Cent ...

  4. 集成环境wamp环境下 memcached的安装

    早就听说过memcached,但是一直没实践过.所有今天有时间就搞了一下,哎废了我一上午才搞定!一上午啊,好丢人.特写记录一下 先说一下我遇到的问题:按照别人教程(还有好多)说的,安装后没有任何的错误 ...

  5. Eclipse 代码提示功能设置。

    1.        解决实例化时自动补全不必要的单词问题 2.        以MyEclipse 6.5重新配图 鉴 于网上的批评之声甚大,我只想说明我的想法:这样的增强代码提示,最终是用来辅助我们 ...

  6. ASP.NET Core 行军记 -----拔营启程

    ASP.NET MVC 6:https://docs.asp.net/en/latest/mvc/index.html ASP.NET Core :https://docs.asp.net/en/la ...

  7. Error NO.2013 Lost connection to Mysql server during query

    系统:[root@hank-yoon ~]# cat /etc/redhat-release CentOS release 6.3 (Final) DB版本:mysql> select @@ve ...

  8. ENVI 5.1操作心得

    1.ENVI中计算的NDVI导出ARCGIS中识别的float数据类型,选择File——save as——erdas img.在ARCGIS中就能统计出NDVI信息 2.如何去掉Nan值从影像中心位置 ...

  9. ios开发之数据的持久化存储机制

    IOS中数据的持久化保存这块内容,类似于Android中文件的几种常见的存储方式. 对于数据的持久化存储,ios中一般提供了4种不同的机制. 1.属性列表 2.对象归档 3.数据库存储(SQLite3 ...

  10. php服务器探针

    <?php /* ---------------------------------------------------- */ /* 程序名称: PHP探针-Yahei /* 程序功能: 探测 ...