search
HomeCommon ProblemWhat is the difference between semaphore and mutex
What is the difference between semaphore and mutexNov 08, 2021 pm 02:24 PM
mutexSignal amountthread

Difference: 1. Mutex is used for mutual exclusion of threads, and semaphore is used for thread synchronization; 2. Mutex value can only be 0 or 1, and semaphore value can be a non-negative integer; 3. The locking and unlocking of the mutex must be used by the same thread respectively. The semaphore can be released by one thread and obtained by another thread.

What is the difference between semaphore and mutex

The operating environment of this tutorial: Windows 7 system, Dell G3 computer.

The difference between mutex and semaphore

1. Mutex is used for mutual exclusion of threads, and semaphore is used for synchronization of threads.

This is the fundamental difference between mutexes and semaphores, that is, the difference between mutual exclusion and synchronization.

Mutual exclusion: refers to a resource that only allows one visitor to access it at the same time, and is unique and exclusive. But mutual exclusion cannot limit the order in which visitors access resources, that is, access is unordered.

Synchronization: refers to the orderly access of resources by visitors through other mechanisms on the basis of mutual exclusion (in most cases). In most cases, synchronization already implements mutual exclusion, especially when all writes to resources must be mutually exclusive. A few cases allow multiple visitors to access resources at the same time

2. The mutex value can only be 0/1, and the semaphore value can be a non-negative integer.

In other words, a mutex can only be used for mutually exclusive access to one resource, and it cannot implement multi-thread mutual exclusion of multiple resources. Semaphore can realize multi-thread mutual exclusion and synchronization of multiple similar resources. When the semaphore is a single-valued semaphore, mutually exclusive access to a resource can also be completed.

3. The locking and unlocking of the mutex must be used by the same thread respectively. The semaphore can be released by one thread and obtained by another thread.

Mutex (Mutex)

The mutex is a data structure that represents the mutual exclusion phenomenon and is also used as a binary semaphore. A mutex is basically a multitasking-sensitive binary signal that can be used to synchronize the behavior of multiple tasks. It is often used to protect critical sections of code from interrupts and to share resources used in synchronization.

What is the difference between semaphore and mutex

Mutex is essentially a lock, providing exclusive access to resources, so the main function of Mutex is for mutual exclusion. The value of the Mutex object has only two values ​​​​0 and 1. These two values ​​​​also represent the two states of Mutex respectively. The value is 0, indicating the locking state. The current object is locked. If the user process/thread attempts to Lock critical resources, it will enter the queue and wait; the value is 1, indicating the idle state. The current object is idle, and the user process/thread can Lock critical resources. Afterwards, the Mutex value decreases by 1 and becomes 0.

Mutex can be abstracted into four operations:

-Create

-Lock

-Unlock

- DestroyDestroy

Mutex can have an initial value when it is created, indicating whether the Mutex is in a locked state or an idle state after it is created. In the same thread, in order to prevent deadlock, the system does not allow the Mutex to be locked twice in a row (the system usually returns immediately after the second call). In other words, the two corresponding operations of locking and unlocking need to be completed in the same thread.

Mutex functions provided in different operating systems:

Deadlock mainly occurs when there are multiple dependent locks, and it occurs when one thread tries to lock the mutex in the opposite order as another thread. How to avoid deadlock is something that should be paid special attention to when using mutexes. .

Generally speaking, there are several unwritten basic principles:

You must obtain a lock before operating on shared resources.

Be sure to release the lock after completing the operation.

Seize the lock for as short a time as possible.

If there are multiple locks, if the acquisition order is ABC chain lock, the release order should also be ABC.

When a thread returns with an error, it should release the lock it acquired.

Perhaps some readers are curious, how to implement the operations of "suspend waiting" and "wake up waiting thread"? Each Mutex has a waiting queue. If a thread wants to wait on the Mutex, it must first add itself to the waiting queue, then set the thread status to sleep, and then call the scheduler function to switch to another thread. If a thread wants to wake up other threads in the waiting queue, it only needs to take out an item from the waiting queue, change its status from sleep to ready, and join the ready queue. Then it may switch to being awakened the next time the scheduler function is executed. the rout.

Under normal circumstances, if the same thread calls lock twice, during the second call, because the lock is already occupied, the thread will hang up and wait for other threads to release the lock. However, the lock is occupied by If the lock is occupied by itself, the thread is suspended without a chance to release the lock, so it is always in a suspended waiting state. This is called deadlock. Another typical deadlock situation is this: Thread A acquires lock 1, and thread B acquires lock 2. At this time, thread A calls lock to try to acquire lock 2. As a result, it needs to hang and wait for thread B to release lock 2, and this At this time, thread B also calls lock to try to obtain lock 1. As a result, it needs to wait for thread A to release lock 1, so both threads A and B are in a suspended state forever. It is not difficult to imagine that if more threads and more locks are involved, the problem of possible deadlock will become complicated and difficult to judge.

Semaphore

Semaphore, sometimes called a semaphore, is a facility used in a multi-threaded environment. It is responsible for coordinating various threads. To ensure that they can use public resources correctly and reasonably.

Semaphore can be divided into several categories:

  • Binary semaphore (binary semaphore): Only the semaphore is allowed to take the value 0 or 1, and it can only be used by one at the same time Thread acquisition.

  • Integer semaphore (integer semaphore): The semaphore value is an integer, which can be obtained by multiple threads at the same time until the semaphore value becomes 0.

  • Record semaphore (record semaphore): In addition to an integer value value (count), each semaphore s also has a waiting queue List, which is blocked on the semaphore. The identification of each thread. When a semaphore is released and the value is incremented by one, the system automatically wakes up a waiting thread from the waiting queue, allowing it to obtain the semaphore, and at the same time the semaphore is decremented by one.

The semaphore controls access to shared resources through a counter. The value of the semaphore is a non-negative integer, and all threads passing it will reduce the integer by one. If the counter is greater than 0, access is allowed and the counter is decremented by 1; if it is 0, access is prohibited and all threads trying to pass it will be in a waiting state.

The result of the counter calculation is the pass allowed to access the shared resource. Therefore, in order to access a shared resource, a thread must get a pass from the semaphore. If the semaphore's count is greater than 0, then this thread gets a pass, which will cause the semaphore's count to be decremented. Otherwise, this thread will block until it gets a pass. until. When this thread no longer needs to access the shared resource, it releases the pass, which causes the semaphore's count to be incremented, and if another thread is waiting for the pass, that thread will get the pass at that time.

Semaphore can be abstracted into five operations:

  • - Create Create

  • - Wait for Wait:

    The thread waits for the semaphore. If the value is greater than 0, it is obtained and the value is reduced by one; if it is only equal to 0, the thread enters the sleep state until the semaphore value is greater than 0 or times out.

  • -Release Post

    executes the release of the semaphore, and the value is increased by one; if there is a waiting thread at this time, the thread is awakened.

  • -Trying to wait for TryWait

    If TryWait is called, the thread does not actually obtain the semaphore, but checks whether the semaphore can be obtained. If the semaphore value is greater than 0, TryWait returns success; otherwise it returns failure.

  • -Destroy

Semaphores can be used to protect two or more key code segments. These key code segments cannot be called concurrently. Before entering a critical section of code, the thread must obtain a semaphore. If there are no threads in the critical section of code, the thread immediately enters that part of the block diagram. Once the critical section of code is complete, the thread must release the semaphore. Other threads that want to enter this critical code section must wait until the first thread releases the semaphore. In order to complete this process, you need to create a semaphore, and then place the Acquire Semaphore VI and Release Semaphore VI at the beginning and end of each key code segment. Make sure that these semaphore VIs refer to the originally created semaphore.

Action/System

Win32

Linyx

Solaris

Create

CreateMutex

##pthread_mutex_init

mutex_init

Lock

WaitForSingleObject

pthread_mutex_lock

mutex_lock

Unlock

ReleaseMutex

pthread_mutex_unlock

mutex_unlock

Destroy

CloseHandle

pthread_mutex_destroy

mutex_destroy

##For more related knowledge, please Visit the

Action/System

Win32

POSIX

Create

CreateSemaphore

##sem_init

Wait

WaitForSingleObject

sem _wait

Release

ReleaseMutex

sem _post

Try to wait

WaitForSingleObject

sem _trywait

Destroy

CloseHandle

sem_destroy

FAQ

section!

The above is the detailed content of What is the difference between semaphore and mutex. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
8核16线程是什么意思?8核16线程是什么意思?Feb 02, 2023 am 11:26 AM

8核是指CPU有8颗物理核心,16线程是指CPU最多同时可以有16个线程处理任务。核心数和线程数是电脑CPU的重要性能指标,CPU的核心数越高处理速度就越高;线程数越多越有利于同时运行多个程序,因为线程数等同于在某个瞬间CPU能同时并行处理的任务数。多线程可最大限度地实现宽发射、乱序的超标量处理,提高处理器运算部件的利用率,缓和由于数据相关或Cache未命中带来的访问内存延时。

PHP程序中的互斥量最佳实践PHP程序中的互斥量最佳实践Jun 07, 2023 pm 12:40 PM

随着时代的进步和技术的不断更新,Web应用程序的需求越来越大,而PHP程序成为了许多Web应用程序的主要编程语言之一。在一个多线程的Web应用程序中,必须考虑到并发性和竞态条件,以确保程序的正确运行。在PHP程序中,互斥量提供了一种解决方案,以确保线程安全和数据传输的准确性。在本文中,我们将探讨PHP程序中的互斥量最佳实践。什么是互斥量?互斥量是用于确保线程

Java错误:JavaFX线程卡顿错误,如何处理和避免Java错误:JavaFX线程卡顿错误,如何处理和避免Jun 24, 2023 pm 05:52 PM

在进行JavaFX应用程序开发的过程中,我们常常会遇到JavaFX线程卡顿错误。这种错误的严重程度不同,可能会对程序的稳定性和性能产生不利的影响。为了保证程序的正常运行,我们需要了解JavaFX线程卡顿错误的原因和解决方法,以及如何预防这种错误的发生。一、JavaFX线程卡顿错误的原因JavaFX是一个多线程的UI应用程序框架,它允许程序在后台线程中执行长时

什么是程序运行时指令流的最小单位什么是程序运行时指令流的最小单位Aug 23, 2022 pm 02:16 PM

“线程”是程序运行时指令流的最小单位。进程是指一个具有一定独立功能的程序,而线程是进程的一部分,描述指令流执行状态;线程是进程中的指令执行流的最小单位,是CPU调度的基本单位。一个线程是一个任务(一个程序段)的一次执行过程;线程不占有内存空间,它包括在进程的内存空间中。在同一个进程内,多个线程共享进程的资源;一个进程至少有一个线程。

go语言中协程与线程的区别是什么go语言中协程与线程的区别是什么Feb 02, 2023 pm 06:10 PM

区别:1、一个线程可以多个协程,一个进程也可以单独拥有多个协程;2、线程是同步机制,而协程则是异步;3、协程能保留上一次调用时的状态,线程不行;4、线程是抢占式,协程是非抢占式的;5、线程是被分割的CPU资源,协程是组织好的代码流程,协程需要线程来承载运行。

我们如何在Java中实现一个计时器线程?我们如何在Java中实现一个计时器线程?Aug 30, 2023 pm 02:49 PM

Timer类安排任务在给定时间运行一次或重复。它还可以作为守护线程在后台运行。要将Timer与守护线程关联起来,需要使用一个带有布尔值的构造函数。计时器以固定延迟和固定速率安排任务。在固定延迟下,如果任何一个执行被系统GC延迟,则其他执行也会延迟,并且每次执行都会延迟对应于之前的执行。在固定速率下,如果任何执行被系统GC延迟,则连续发生2-3次执行以覆盖与第一次执行开始时间相对应的固定速率。Timer类提供了cancel()方法来取消计时器。当调用该方法时,定时器终止。Timer类仅执行实现Ti

Java使用Thread类的stop()函数强制终止线程的执行Java使用Thread类的stop()函数强制终止线程的执行Jul 26, 2023 am 09:28 AM

Java使用Thread类的stop()函数强制终止线程的执行在Java多线程编程中,有时候我们需要强制终止一个正在执行的线程。Java提供了Thread类的stop()函数来实现线程的强制终止。本文将介绍stop()函数的用法,并提供代码示例来说明。在介绍stop()函数之前,我们先了解一下Thread类的几个常用方法:start():启动线程,使线程进入

Microsoft计划在Windows上的Outlook经典应用程序中引入AI驱动的CopilotMicrosoft计划在Windows上的Outlook经典应用程序中引入AI驱动的CopilotOct 19, 2023 pm 11:13 PM

Microsoft显然不会将其强大的人工智能支持的Copilot工具保留为新应用程序的独家功能。现在,该公司刚刚宣布计划在Windows上的Outlook经典应用程序中引入Copilot。正如其365路线图网站上发布的那样,预览将于明年<>月开始,直到<>月在当前频道的桌面上在全球范围内推出。Copilot是一种生产力工具,它使用大型语言模型(LLM)来帮助用户完成编写电子邮件、汇总文档和翻译语言等任务。它的主要功能之一是它能够总结电子邮件

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor