之一的意思是什么| 软件测试需要学什么| 胆固醇高对身体有什么危害| 喉咙干吃什么药| 我操是什么意思| 放射治疗是什么意思| 祖字五行属什么| 什么叫封闭针| 早泄吃什么药最好| 验尿白细胞高是什么原因| 宫腔内无回声区是什么意思| beside是什么意思| 低血压吃什么药效果好| 王八蛋是什么意思| 炎热的夏天风儿像什么| pr间期缩短是什么意思| 孩子半夜咳嗽是什么原因| 长脸适合什么眉形| 皮肤黑穿什么颜色的衣服好看| 去乙酰毛花苷又叫什么| 参数错误是什么意思| 五行海中金是什么意思| 1989年属什么的| 北京的简称是什么| 小腿冰凉是什么原因| jojo是什么意思| 月经提前了10天是什么原因| 张飞的武器是什么| 在什么情况下需要做肠镜| 部分导联st段改变是什么意思| 谷氨酰基转移酶低是什么原因| 红花泡水喝有什么功效| 心急如焚是什么意思| 夏天晚饭吃什么比较好| 7.23什么星座| 什么药治便秘| 俺是什么意思| 什么叫无产阶级| 金色搭配什么颜色好看| 有什么不能说| 81是什么意思| 吐白沫是什么原因| 白带多用什么药效果好| 岁月如歌什么意思| 实至名归是什么意思| 纯棉是什么面料| 跳跳糖为什么会跳| 血管瘤挂什么科比较好| 拉不出来屎是什么原因| 肝左叶囊性灶什么意思| 胰岛素是干什么用的| 惊蛰是什么季节的节气| 阑尾炎打什么消炎针好| 七月七是什么节日| 牛油果是什么味道| 人体有365个什么| 湿热会引起什么症状| 1971年属猪的是什么命| 高血糖吃什么药| 顺子是什么意思| 西同念什么| 干涉是什么意思| 吃什么对肺最好| 盐酸氯米帕明片有什么作用| 2020年是什么年| 咬肌疼是什么原因| 脑震荡后眩晕吃什么药| 滑膜炎吃什么药最好| 阳痿什么症状| 希五行属什么| 去肝火喝什么茶效果最好| 吃什么食物可以降低尿酸| ap手表是什么牌子| 全身是宝的动物是什么生肖| 手指疣初期什么样子| 乳头瘤是什么病| 回族为什么不能吃猪肉| 蒲公英什么时候开花| 耷拉是什么意思| beyond什么意思| 茶学专业学什么| 弱碱性水是什么水| 牙龈肿痛吃什么中成药| 失足是什么意思| 为什么新疆人长得像外国人| 夏天吃什么降火| 露从今夜白下一句是什么| 酒不醉人人自醉是什么意思| 苹果像什么| 头发的主要成分是什么| 先天是什么意思| 胆固醇低是什么原因| 孩子大便出血什么原因| 捆是什么意思| 漏尿是什么原因造成的| 狗牯脑茶属于什么茶| 每天吃洋葱有什么好处| 阳痿挂什么科| 四维彩超什么时候做| 痛风可以吃什么水果| 素手是什么意思| 细胞核由什么组成| 制片人是什么意思| 手上起小水泡痒是什么原因| 牙疼吃什么饭菜比较好| 周杰伦为什么喜欢昆凌| ir是什么意思| 什么水果糖分低| 暖气是什么意思| 舌头短的人意味着什么| 念想是什么意思| 梦到被蜜蜂蛰是什么意思| 炖鸡放什么调料好吃| 清热败火的败是什么意思| 血沉高说明什么问题| 罗姓男孩取什么名字好| 品牌pr是什么意思| 静脉曲张吃什么中成药| lee中文叫什么| 食指有痣代表什么意思| 6月26号是什么星座| 面膜什么牌子好| 糖尿病人适合吃什么水果| 血蛋白低是什么原因| 金牛座前面是什么星座| 需要是什么意思| 脊灰疫苗是预防什么的| 舌息心念什么| 梦见自己生了个女孩是什么意思| ace是什么意思| rio是什么酒| 天天睡觉做梦是什么原因| 女人下身干燥无水是什么原因| 龙象征着什么| 旅拍什么意思| 薄荷有什么功效和作用| 什么药能治阳痿早泄| 朱砂是什么意思| 南什么北什么的成语| 黑话是什么意思| 中医讲肾主什么| 进产房吃什么补充体力| 皮试是什么| 月半是什么意思| 月经褐色是什么原因| 血脂稠喝什么茶效果好| 声情并茂的意思是什么| 韩语欧巴是什么意思| 什么什么大叫| 怀孕了吃什么药能打掉| 重阳节是什么意思| 北京为什么是首都| 台甫是什么意思| 为什么一低头就晕| 胃酸吃什么| 吃鱼油有什么好处| 咳血鲜红是什么病呢| 争宠是什么意思| 败血症是什么症状| 手指甲发紫是什么原因| 越来越瘦是什么原因| 胎记是什么| 什么病会传染人| 血管瘤有什么危害| 16岁属什么| 乜贴是什么意思| 人参归脾丸适合什么人吃| 睡觉总是做梦是什么原因| 做完人流需要注意什么| 撩是什么意思| 吹风扇感冒了吃什么药| 甲状腺回声不均匀什么意思| 小孩病毒性感冒吃什么药效果好| 大山羊是什么病| 补充蛋白质吃什么最好| 燃气灶什么品牌好| approval是什么意思| 湿热内蕴是什么意思| 倒钩是什么意思| bmi是什么意思| 秦始皇叫什么名字| 手抽筋是什么原因| 乳腺囊肿有什么症状| 缘是什么生肖| 表里不一是什么意思| 最近有什么病毒| 丘疹用什么药膏最有效| 什么情况需要根管治疗| 瓜子脸适合什么发型| 喜欢白色的女人是什么性格| 王是什么生肖| 佛系是什么意思啊| 与其让你在我怀中枯萎是什么歌| 儿童感冒流鼻涕吃什么药好得快| cy什么意思| 痰湿体质吃什么食物好| 正的五行属性是什么| 两小儿辩日告诉我们什么道理| 头皮痒用什么止痒最好| 存是什么生肖| 紫河车是什么东西| 81年属什么| 五浊恶世是什么意思| 18是什么生肖| 药鱼用什么药效果最好| 内膜是什么| 天天都需要你爱是什么歌| 91网站是什么| 欺骗餐是什么意思| 员外是什么生肖| 中耳炎吃什么药最有效| 为非作歹是什么意思| 总蛋白偏低是什么原因| 腹泻恶心想吐是什么原因| 缺氯有什么症状怎么补| 急性肠胃炎吃什么药效果好| npn是什么意思| 手容易出汗是什么原因| 月经血块是什么原因| 来月经吃什么水果好| 苦衷是什么意思| 刺猬的刺有什么作用| 月经太多是什么原因| 继发性高血压是什么意思| 化干戈为玉帛是什么意思| 非营利性医院是什么意思| 今天什么属相| 呕吐腹泻是什么原因| 乙肝表面抗原阳性是什么意思| 胆固醇低是什么原因| nokia是什么牌子的手机| 蜗牛什么梗| 撒丫子是什么意思| 患得患失是什么意思| 梦到活人死了是什么预兆| 血管堵塞吃什么药| 人体七大营养素是什么| 冰菜是什么菜| 张飞穿针歇后语下一句是什么| 精神恍惚是什么症状| 昙花一现什么意思| 白包是什么意思| 卤素灯是什么灯| hpv阳性是什么病| 918是什么日子| 谭字五行属什么| 什么叫口腔溃疡| 9月20日是什么星座| 脸上白了一小块是什么原因| 发烧惊厥是什么症状| 屋里有蝙蝠有什么预兆| 五一广场有什么好玩的| 劳士顿手表什么档次| 低血压挂什么科| 牙龈肿痛吃什么水果| 硒片什么牌子好| 白带像豆腐渣用什么药| 用盐洗脸有什么好处| 非甾体抗炎药是什么意思| 老是嗜睡是什么原因| 去医院查怀孕挂什么科| 右手臂痛是什么预兆| 帅t是什么意思| nlp是什么| 百度

威海修复岸线62公里沙滩30万平方米湿地万余亩

百度 来源:学习时报

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
吃什么补气血最快最好 什么是碱中毒 汗臭味很重是什么原因引起的 一什么铅笔 遇见是什么意思
口臭口苦吃什么药最好 艾滋病早期有什么症状 突然抽搐是什么原因 鸡蛋胶是什么鱼胶 胃胀吃什么药最有效
骨折吃什么好的快 一百万存款算什么水平 白带带血是什么原因 食人鱼长什么样子 市盈率是什么意思
九价疫苗是什么 割包皮有什么用 农历9月28日是什么星座 什么是中国 pubg是什么意思
圆寂什么意思hcv8jop5ns2r.cn 手掌心出汗是什么原因jiuxinfghf.com 口加女念什么onlinewuye.com 经常吃海带有什么好处和坏处hcv8jop5ns8r.cn 脾门区结节是什么意思zsyouku.com
天蝎女跟什么星座最配hcv7jop9ns5r.cn 梦见卖衣服是什么意思1949doufunao.com 右附件区囊肿是什么意思hcv8jop5ns2r.cn 什么乎乎hcv8jop3ns5r.cn 尿很臭是什么原因女性96micro.com
背后长痘痘是什么原因96micro.com 胎盘埋在什么地方最好hcv8jop6ns0r.cn 吃什么可以降糖hcv9jop8ns0r.cn 晒伤了涂什么药hcv9jop3ns3r.cn 花孔雀是什么意思hcv9jop3ns9r.cn
吃什么补筋和韧带最快hcv8jop7ns4r.cn 吃什么可以提高记忆力hcv8jop5ns3r.cn 4月25日什么星座hcv8jop0ns8r.cn 泡鲁达是什么hcv9jop0ns1r.cn vps是什么hcv9jop3ns0r.cn
百度