麸皮是什么| 后脑袋疼是什么原因| 红粉是什么意思| 黄绿色痰液是什么感染| 一什么水珠| 女生的隐私长什么样子| 值神是什么意思| 手足口病忌口什么食物| 给你脸了是什么意思| jerry英文名什么意思| 处是什么结构| 神话是什么意思| 胸部什么时候停止发育| 什么是尿酸高| 志五行属什么| 排骨炖什么比较好吃| 念珠菌用什么药最好| 市委副秘书长什么级别| 警察在古代叫什么| 高职本科是什么意思| 糖尿病人可以吃什么| 豆角没熟中毒什么症状| 中水是什么水| yq是什么意思| 忘川是什么意思| 马的尾巴有什么作用| 日本为什么要侵略中国| 陈赫开的火锅店叫什么| 肚子疼想吐是什么原因| 右眼跳代表什么| 瘘管是什么病| 晚上十二点是什么时辰| 尿频繁是什么原因| 血氧低是什么原因| 尿蛋白2十吃什么药| 好无奈是什么意思| 羊水破了什么感觉| 身上汗味重是什么原因| 看到壁虎是什么征兆| 为什么睡觉会出汗| 结核抗体阳性说明什么| 早射吃什么药可以调理| 银饰发黑是什么原因| 2月15日是什么星座| 人缺钾有什么症状| 5月2号是什么星座| 盗汗挂什么科| 北京大学校长什么级别| 痛风不能吃什么食物表| 船只是什么意思| 什么是数位板| 什么叫放射性疼痛| 火车动车高铁有什么区别| sad是什么意思| 灵枢是什么意思| 华西医院院长什么级别| 什么是点天灯| 椰子鞋是什么牌子| 纸老虎是什么意思| 肾结石什么不可以吃| 狗为什么不吃饭| 女人打呼噜是什么原因| 小孩阑尾炎是由什么原因引起的| 水痘疤痕用什么药膏| 三唑仑是什么药| 来龙去脉是什么意思| 血小板低会有什么症状| 丁丁是什么意思| 尿液浑浊是什么原因| 化疗前要做什么检查| 瘪嘴是什么意思| 亡羊补牢的亡是什么意思| 卡不当什么意思| 运交华盖是什么意思| 国家为什么重视合肥| 蛇胆疮是什么原因引起的| 指甲有竖纹吃什么药| 鹿角菜是什么植物| 喊麦什么意思| 领袖是什么意思| 粉红是什么意思| 精神分裂是什么| 12月15日是什么星座| 金牛座女和什么星座最配| 祖马龙是什么档次| 弱智的人有什么表现| 一动就出汗是什么原因| 二甲双胍缓释片什么时候吃| 断头路是什么意思| 恒字属于五行属什么| 胆囊壁胆固醇结晶是什么意思| 肺热会引起什么症状| 为什么气血不足| 夏令时是什么意思| 闫和阎有什么区别| 间歇性跛行见于什么病| luxury什么牌子| 七月开什么花| 梦见好多蛇是什么意思| 阿胶什么季节吃最好| 阴道炎应该吃什么药| 女性胆固醇高吃什么| 一步两步三步四步望着天是什么歌| 吃什么能长头发| 乔顿男装属于什么档次| 凌晨一点是什么时辰| 房颤有什么危害| 前纵韧带钙化是什么意思| 为什么经常打嗝| 羊肉汤放什么调料| 束带是什么| 康复治疗学什么| 梦见老鼠是什么意思| 为什么发动文化大革命| 什么是神话故事| 尿酸高是什么问题| 滚床单是什么意思| 放疗为什么死得更快| 太阳星座是什么意思| 流泪痣是什么意思| 什么食物含锌多| 绿幽灵五行属什么| 机械性窒息死亡是什么意思| 梦见蛇挡路是什么意思| 8000年前是什么朝代| 肺阳虚吃什么中成药| 什么有洞天| 女生问你喜欢她什么怎么回答| 阴阳是什么意思| 小拇指旁边的手指叫什么| 室性早搏吃什么药| 牛油果是什么季节的水果| 天然气主要成分是什么| 长白毛是什么原因| 木冉读什么| 西泮片是什么药| 办理结婚证需要什么材料| 老实人为什么总被欺负| 羊胡子疮用什么药膏| 以什么为准| 脚气挂什么科室| 酸入肝是什么意思| 牙齿发软是什么原因| 什么斗艳| 异化是什么意思| 青榄配什么煲汤止咳做法| 因应是什么意思| 雾霾蓝配什么颜色好看| 私密瘙痒是什么原因| 火烧是什么食物| 脖子皮肤黑是什么原因| 什么发色显白| 可小刀是什么意思| 为什么会得脂溢性皮炎| 右耳痒是什么预兆| 芹菜吃多了会有什么影响| 上课什么坐姿可以瘦腿| 中暑头晕吃什么药| 小腿疼是什么原因| 男士感染霉菌用什么药| 睡觉做梦多是什么原因| 人体含量最多的元素是什么| 葛根和什么搭配泡水好| 金蝉子是什么佛| 漫不经心是什么意思| 床褥是什么| 泪崩是什么意思| ca125高是什么原因| 7月4日是什么星座| 余田是什么字| 什么品种的榴莲最好吃| oto是什么意思| op什么意思| 来月经头晕是什么原因| 钢镚是什么意思| 海洋中最多的生物是什么| 青年是什么意思| g18k是什么金| 临界是什么意思| 悟空是什么意思| 2007年是什么生肖| 烂嘴角是什么原因| 农历五月二十八是什么日子| 阴阳水是什么水| 生长发育挂什么科| 什么是科学| 至多是什么意思| phe是什么氨基酸| 白热化阶段是什么意思| 女左上眼皮跳是什么预兆| 10月3号是什么星座| 为什么会得乙肝| 跑团是什么| 黄盖代表什么生肖| 勉铃是什么| 4月是什么星座的| 有胆结石的人不能吃什么东西| 纹银是什么意思| 飞地是什么意思| 晚上剪指甲有什么说法| 孺子可教什么意思| 手足口病疫苗什么时候打| 什么是情趣| 八项规定的内容是什么| 十年什么婚| 野生天麻长什么样图片| 岳云鹏为什么这么火| 虾皮不能和什么一起吃| 爱是什么东西| 祥林嫂是什么样的人| 洛阳有什么好吃的| 子宫肌瘤是什么原因导致的| 喜欢是什么| 甲基是什么| 你最喜欢的食物是什么| 糖类抗原ca199偏高是什么原因| 什么是公因数| 肺炎不能吃什么东西| 真菌感染用什么药好| 王八看绿豆是什么意思| 什么是丹凤眼| 糜烂是什么意思| 圣诞是什么意思| 什么是复句| 背胀是什么原因| 50公斤发什么物流便宜| 夏天为什么容易拉肚子| 软组织肿胀是什么意思| 猎德有什么好玩的| 木耳不能和什么食物一起吃| 骨折吃什么药| 比值是什么| 1977属什么| ca125是什么| 见字如面什么意思| 嘴唇发紫发黑是什么原因| 患难见真情是什么意思| 口舌是非是什么意思| 什么血型最招蚊子| 6月13日是什么星座| 乔迁送什么| 谷氨酰转移酶高是什么原因| 嘉字属于五行属什么| 过去的日子叫什么日| dm医学上是什么意思| 甲功不正常会得什么病| 脸上涂什么可以美白| 同比和环比是什么意思| 阶级是什么意思| 凤尾是什么菜| 为什么拉黑色的屎| 舌苔发黑是什么原因引起的| 加盟什么品牌好| 桔梗是什么东西| 2月2日什么星座| 适宜是什么意思| www是什么| 这什么情况| 什么叫甲亢病| 封神是什么意思| 骨折吃什么钙片| 枫叶什么颜色| 治疗勃起困难有什么药| 育字五行属什么| 百度

林依晨时隔五年再演古装剧 搭戏古装小生引粉丝期待

百度 黎明女友和赛车男友15年开始交往,两人经常甜蜜合影、看着非常恩爱,不过日前大部分照片已经被黎明女友删除,可能已经做好当天王嫂的准备。

In computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple threads and avoid critical section problems in a concurrent system such as a multitasking operating system. Semaphores are a type of synchronization primitive. A trivial semaphore is a plain variable that is changed (for example, incremented or decremented, or toggled) depending on programmer-defined conditions.

A useful way to think of a semaphore as used in a real-world system is as a record of how many units of a particular resource are available, coupled with operations to adjust that record safely (i.e., to avoid race conditions) as units are acquired or become free, and, if necessary, wait until a unit of the resource becomes available.

Though semaphores are useful for preventing race conditions, they do not guarantee their absence. Semaphores that allow an arbitrary resource count are called counting semaphores, while semaphores that are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores and are used to implement locks.

The semaphore concept was invented by Dutch computer scientist Edsger Dijkstra in 1962 or 1963,[1] when Dijkstra and his team were developing an operating system for the Electrologica X8. That system eventually became known as the THE multiprogramming system.

Library analogy

edit

Suppose a physical library has ten identical study rooms, to be used by one student at a time. Students must request a room from the front desk. If no rooms are free, students wait at the desk until someone relinquishes a room. When a student has finished using a room, the student must return to the desk and indicate that the room is free.

In the simplest implementation, the clerk at the front desk knows only the number of free rooms available. This requires that all of the students use their room while they have signed up for it and return it when they are done. When a student requests a room, the clerk decreases this number. When a student releases a room, the clerk increases this number. The room can be used for as long as desired, and so it is not possible to book rooms ahead of time.

In this scenario, the front desk count-holder represents a counting semaphore, the rooms are the resource, and the students represent processes/threads. The value of the semaphore in this scenario is initially 10, with all rooms empty. When a student requests a room, they are granted access, and the value of the semaphore is changed to 9. After the next student comes, it drops to 8, then 7, and so on. If someone requests a room and the current value of the semaphore is 0,[2] they are forced to wait until a room is freed (when the count is increased from 0). If one of the rooms was released, but there are several students waiting, then any method can be used to select the one who will occupy the room (like FIFO or randomly picking one). And of course, a student must inform the clerk about releasing their room only after really leaving it.

Important observations

edit

When used to control access to a pool of resources, a semaphore tracks only how many resources are free. It does not keep track of which of the resources are free. Some other mechanism (possibly involving more semaphores) may be required to select a particular free resource.

The paradigm is especially powerful because the semaphore count may serve as a useful trigger for a number of different actions. The librarian above may turn the lights off in the study hall when there are no students remaining, or may place a sign that says the rooms are very busy when most of the rooms are occupied.

The success of the protocol requires applications to follow it correctly. Fairness and safety are likely to be compromised (which practically means a program may behave slowly, act erratically, hang, or crash) if even a single process acts incorrectly. This includes:

  • requesting a resource and forgetting to release it;
  • releasing a resource that was never requested;
  • holding a resource for a long time without needing it;
  • using a resource without requesting it first (or after releasing it).

Even if all processes follow these rules, multi-resource deadlock may still occur when there are different resources managed by different semaphores and when processes need to use more than one resource at a time, as illustrated by the dining philosophers problem.

Semantics and implementation

edit

Counting semaphores are equipped with two operations, historically denoted as P and V (see § Operation names for alternative names). Operation V increments the semaphore S, and operation P decrements it.

The value of the semaphore S is the number of units of the resource that are currently available. The P operation wastes time or sleeps until a resource protected by the semaphore becomes available, at which time the resource is immediately claimed. The V operation is the inverse: it makes a resource available again after the process has finished using it. One important property of semaphore S is that its value cannot be changed except by using the V and P operations.

A simple way to understand wait (P) and signal (V) operations is:

  • wait: Decrements the value of the semaphore variable by 1. If the new value of the semaphore variable is negative, the process executing wait is blocked (i.e., added to the semaphore's queue). Otherwise, the process continues execution, having used a unit of the resource.
  • signal: Increments the value of the semaphore variable by 1. After the increment, if the pre-increment value was negative (meaning there are processes waiting for a resource), it transfers a blocked process from the semaphore's waiting queue to the ready queue.

Many operating systems provide efficient semaphore primitives that unblock a waiting process when the semaphore is incremented. This means that processes do not waste time checking the semaphore value unnecessarily.

The counting semaphore concept can be extended with the ability to claim or return more than one "unit" from the semaphore, a technique implemented in Unix. The modified V and P operations are as follows, using square brackets to indicate atomic operations, i.e., operations that appear indivisible to other processes:

function V(semaphore S, integer I):
    [S ← S + I]

function P(semaphore S, integer I):
    repeat:
        [if S ≥ I:
        S ← S ? I
        break]

However, the rest of this section refers to semaphores with unary V and P operations, unless otherwise specified.

To avoid starvation, a semaphore has an associated queue of processes (usually with FIFO semantics). If a process performs a P operation on a semaphore that has the value zero, the process is added to the semaphore's queue and its execution is suspended. When another process increments the semaphore by performing a V operation, and there are processes on the queue, one of them is removed from the queue and resumes execution. When processes have different priorities the queue may be ordered thereby, such that the highest priority process is taken from the queue first.

If the implementation does not ensure atomicity of the increment, decrement, and comparison operations, there is a risk of increments or decrements being forgotten, or of the semaphore value becoming negative. Atomicity may be achieved by using a machine instruction that can read, modify, and write the semaphore in a single operation. Without such a hardware instruction, an atomic operation may be synthesized by using a software mutual exclusion algorithm. On uniprocessor systems, atomic operations can be ensured by temporarily suspending preemption or disabling hardware interrupts. This approach does not work on multiprocessor systems where it is possible for two programs sharing a semaphore to run on different processors at the same time. To solve this problem in a multiprocessor system, a locking variable can be used to control access to the semaphore. The locking variable is manipulated using a test-and-set-lock command.

Examples

edit

Trivial example

edit

Consider a variable A and a boolean variable S. A is only accessed when S is marked true. Thus, S is a semaphore for A.

One can imagine a stoplight signal (S) just before a train station (A). In this case, if the signal is green, then one can enter the train station. If it is yellow or red (or any other color), the train station cannot be accessed.

Login queue

edit

Consider a system that can only support ten users (S=10). Whenever a user logs in, P is called, decrementing the semaphore S by 1. Whenever a user logs out, V is called, incrementing S by 1 representing a login slot that has become available. When S is 0, any users wishing to log in must wait until S increases. The login request is enqueued onto a FIFO queue until a slot is freed. Mutual exclusion is used to ensure that requests are enqueued in order. Whenever S increases (login slots available), a login request is dequeued, and the user owning the request is allowed to log in. If S is already greater than 0, then login requests are immediately dequeued.

Producer–consumer problem

edit

In the producer–consumer problem, one process (the producer) generates data items and another process (the consumer) receives and uses them. They communicate using a queue of maximum size N and are subject to the following conditions:

  • the consumer must wait for the producer to produce something if the queue is empty;
  • the producer must wait for the consumer to consume something if the queue is full.

The semaphore solution to the producer–consumer problem tracks the state of the queue with two semaphores: emptyCount, the number of empty places in the queue, and fullCount, the number of elements in the queue. To maintain integrity, emptyCount may be lower (but never higher) than the actual number of empty places in the queue, and fullCount may be lower (but never higher) than the actual number of items in the queue. Empty places and items represent two kinds of resources, empty boxes and full boxes, and the semaphores emptyCount and fullCount maintain control over these resources.

The binary semaphore useQueue ensures that the integrity of the state of the queue itself is not compromised, for example, by two producers attempting to add items to an empty queue simultaneously, thereby corrupting its internal state. Alternatively a mutex could be used in place of the binary semaphore.

The emptyCount is initially N, fullCount is initially 0, and useQueue is initially 1.

The producer does the following repeatedly:

produce:
    P(emptyCount)
    P(useQueue)
    putItemIntoQueue(item)
    V(useQueue)
    V(fullCount)

The consumer does the following repeatedly

consume:
    P(fullCount)
    P(useQueue)
    item ← getItemFromQueue()
    V(useQueue)
    V(emptyCount)

Below is a substantive example:

  1. A single consumer enters its critical section. Since fullCount is 0, the consumer blocks.
  2. Several producers enter the producer critical section. No more than N producers may enter their critical section due to emptyCount constraining their entry.
  3. The producers, one at a time, gain access to the queue through useQueue and deposit items in the queue.
  4. Once the first producer exits its critical section, fullCount is incremented, allowing one consumer to enter its critical section.

Note that emptyCount may be much lower than the actual number of empty places in the queue, for example, where many producers have decremented it but are waiting their turn on useQueue before filling empty places. Note that emptyCount + fullCount ≤ N always holds, with equality if and only if no producers or consumers are executing their critical sections.

Passing the baton pattern

edit

The "Passing the baton" pattern[3][4][5] proposed by Gregory R. Andrews is a generic scheme to solve many complex concurrent programming problems in which multiple processes compete for the same resource with complex access conditions (such as satisfying specific priority criteria or avoiding starvation). Given a shared resource, the pattern requires a private "priv" semaphore (initialized to zero) for each process (or class of processes) involved and a single mutual exclusion "mutex" semaphore (initialized to one). The pseudo-code for each process is:

void process(int proc_id, int res_id)
{
	resource_acquire(proc_id, res_id);
	
	<use the resource res_id>;
	
	resource_release(proc_id, res_id);
}

The pseudo-code of the resource acquisition and release primitives are:

void resource_acquire(int proc_id, int res_id)
{
	P(mutex);
	
	if(<the condition to access res_id is not verified for proc_id>)
	{
		<indicate that proc_id is suspended for res_id>;
		V(mutex);
		P(priv[proc_id]);
		<indicate that proc_id is not suspended for res_id anymore>;
	}
	
	<indicate that proc_id is accessing the resource>;
	
	pass_the_baton(); // See below
}
void resource_release(int proc_id, int res_id)
{
	P(mutex);
	
	<indicate that proc_id is not accessing the resource res_id anymore>;
	
	pass_the_baton(); // See below
}

Both primitives in turn use the "pass_the_baton" method, whose pseudo-code is:

void pass_the_baton(int res_id)
{
	if <the condition to access res_id is true for at least one suspended process>
	{
		int p = <choose the process to wake>;
		V(priv[p]);
	}
	else
	{
		V(mutex);
	}
}

Remarks

The pattern is called "passing the baton" because a process that releases the resource as well as a freshly reactivated process will activate at most one suspended process, that is, shall "pass the baton to it". The mutex is released only when a process is going to suspend itself (resource_acquire), or when pass_the_baton is unable to reactivate another suspended process.

Operation names

edit

The canonical names V and P come from the initials of Dutch words. V is generally explained as verhogen ("increase"). Several explanations have been offered for P, including proberen ("to test" or "to try"),[6] passeren ("pass"), and pakken ("grab"). Dijkstra's earliest paper on the subject[1] gives passering ("passing") as the meaning for P, and vrijgave ("release") as the meaning for V. It also mentions that the terminology is taken from that used in railroad signals. Dijkstra subsequently wrote that he intended P to stand for prolaag,[7] short for probeer te verlagen, literally "try to reduce", or to parallel the terms used in the other case, "try to decrease".[8][9][10]

In ALGOL 68, the Linux kernel,[11] and in some English textbooks, the V and P operations are called, respectively, up and down. In software engineering practice, they are often called signal and wait,[12] release and acquire[12] (standard Java library),[13] or post and pend. Some texts call them vacate and procure to match the original Dutch initials.[14][15]

Semaphores vs. mutexes

edit

A mutex is a locking mechanism that sometimes uses the same basic implementation as the binary semaphore. However, they differ in how they are used. While a binary semaphore may be colloquially referred to as a mutex, a true mutex has a more specific use-case and definition, in that only the task that locked the mutex is supposed to unlock it. This constraint aims to handle some potential problems of using semaphores:

  1. Priority inversion: If the mutex knows who locked it and is supposed to unlock it, it is possible to promote the priority of that task whenever a higher-priority task starts waiting on the mutex.
  2. Premature task termination: Mutexes may also provide deletion safety, where the task holding the mutex cannot be accidentally deleted. [citation needed] (This is also a cost; if the mutex can prevent a task from being reclaimed, then a garbage collector has to monitor the mutex.)
  3. Termination deadlock: If a mutex-holding task terminates for any reason, the OS can release the mutex and signal waiting tasks of this condition.
  4. Recursion deadlock: a task is allowed to lock a reentrant mutex multiple times as it unlocks it an equal number of times.
  5. Accidental release: An error is raised on the release of the mutex if the releasing task is not its owner.

See also

edit

References

edit
  1. ^ a b Dijkstra, Edsger W. Over de sequentialiteit van procesbeschrijvingen (EWD-35) (PDF). E.W. Dijkstra Archive. Center for American History, University of Texas at Austin. (transcription) (undated, 1962 or 1963)
  2. ^ The Little Book of Semaphores Allen B. Downey
  3. ^ Andrews, Gregory R. (1999). Foundations of Multithreaded, Parallel, and Distributed Programming. Addison-Wesley.
  4. ^ Carver, Richard H.; Thai, Kuo-Chung (2005). Modern Multithreading: Implementing, Testing, and Debugging Multithreaded Java and C++/Pthreads/Win32 Programs. Wiley.
  5. ^ Maurer, Christian (2021). Nonsequential and Distributed Programming with Go. Springer.
  6. ^ Silberschatz, Abraham; Galvin, Peter Baer; Gagne, Greg (2008), Operating System Concepts (8th ed.), John Wiley & Sons. Inc, p. 234, ISBN 978-0-470-12872-5
  7. ^ Dijkstra, Edsger W. EWD-74 (PDF). E.W. Dijkstra Archive. Center for American History, University of Texas at Austin. (transcription)
  8. ^ Dijkstra, Edsger W. MULTIPROGAMMERING EN DE X8 (EWD-51) (PDF). E.W. Dijkstra Archive. Center for American History, University of Texas at Austin. (transcription) (in Dutch)
  9. ^ Dijkstra's own translation reads "try-and-decrease", although that phrase might be confusing for those unaware of the colloquial "try-and..."
  10. ^ (PATCH 1/19) MUTEX: Introduce simple mutex implementation Linux Kernel Mailing List, 19 December 2005
  11. ^ Linux Kernel hacking HOWTO Archived 2025-08-07 at the Wayback Machine LinuxGrill.com
  12. ^ a b Mullender, Sape; Cox, Russ (2008). Semaphores in Plan 9 (PDF). 3rd International Workshop on Plan 9.
  13. ^ java.util.concurrent.Semaphore
  14. ^ "exec.library/Procure". amigadev.elowar.com. Retrieved 2025-08-07.
  15. ^ "exec.library/Vacate". amigadev.elowar.com. Retrieved 2025-08-07.
edit

Introductions

edit

References

edit
农历六月六日是什么节日 afp是什么 为什么会湿气重 乙状结肠腺瘤是什么病 鱼腥草不能和什么一起吃
户籍所在地是指什么 一月18号是什么星座 为什么会流鼻涕 湿疹要注意什么 pdd是什么
理化检验主要检验什么 静脉曲张挂什么号 aids是什么意思 身份证最后四位数代表什么 女性体寒 吃什么好
榴莲和什么水果相克 医保和社保有什么区别 手热脚凉是什么原因 脂肪瘤看什么科 甘油三酯高吃什么降得快
省长什么级别hcv8jop4ns8r.cn 痔疮长什么样子hcv9jop0ns8r.cn 北加田加共是什么字hcv8jop3ns7r.cn 哥伦比亚牌子什么档次hcv9jop2ns6r.cn 什么叫增强ctwuhaiwuya.com
cy什么意思hcv8jop0ns8r.cn 什么叫周围神经病hcv9jop6ns8r.cn 吃什么水果可以变白hcv9jop1ns9r.cn 试管是什么意思hcv8jop4ns9r.cn 宫颈息肉有什么危害xinjiangjialails.com
冉字五行属什么hcv8jop8ns1r.cn 房水是什么hcv9jop4ns6r.cn 什么是性骚扰hcv7jop4ns5r.cn 眉心长痘是什么原因hcv7jop4ns6r.cn 胃肠感冒可以吃什么水果hcv9jop8ns3r.cn
什么叫双相障碍hcv9jop2ns1r.cn 上眼皮有痣代表什么hcv9jop4ns0r.cn 肠溶片是什么意思hcv8jop1ns0r.cn 飞行模式和关机有什么区别hcv8jop3ns0r.cn 心肌梗塞是什么症状hcv7jop7ns2r.cn
百度