三个毛念什么字| 为什么会拉黑屎| 验孕棒阳性代表什么| 敲打是什么意思| 老是出汗是什么原因| 戾气是什么| 移植后吃什么水果好| 正太是什么| 孕激素六项检查什么时候做| 心形脸适合什么发型| 剖腹产吃什么下奶最快| 血精是什么原因| 知了长什么样| click什么意思| 左侧腰疼是什么原因| 孕囊是什么意思| 孕妇刚生完孩子吃什么好| 女人晚上盗汗是什么原因| 早泄是什么| 尿酸高能吃什么| 嘴巴旁边长痘痘是为什么| 玻璃心是什么意思| 骨折吃什么水果好| 女性血热吃什么好得快| 急性子是什么意思| 诈尸是什么意思| 七月七是什么星座| 为什么会有结石| 手发麻发木是什么病的前兆| 1936年中国发生了什么| 生化全套主要检查什么| 骨龄是什么| 今年什么时候过年| 扁桃体肿大是什么原因引起的| 牛排炖什么好吃| 赫五行属性是什么| 妇科炎症用什么药| 胆囊息肉有什么症状| c919是什么意思| 舌头白腻厚苔是什么原因| 蝴蝶骨是什么| 尿胆原弱阳性什么意思| 心脏传导阻滞吃什么药| 什么关系| 凝血功能是什么意思| 脑白质变性什么意思| 432是什么意思| 水猴子是什么| 柱镜度数是什么意思| 什么叫微创手术| 姓兰的是什么民族| 聪明的近义词是什么| 脖子不舒服看什么科| 胪是什么意思| 金牛女喜欢什么样的男生| 鹿角粉有什么功效和作用| 胆囊炎什么症状| 涉黑是什么意思| 大手牵小手是什么菜| 一帘幽梦是什么意思| 分散片是什么意思| 如泰山前面一个字是什么啊| 吃什么可以偷偷流产| 月经提前10天正常吗是什么原因| 画蛇添足的故事告诉我们什么道理| 五步蛇长什么样| 2019年是什么生肖| 主管是什么级别| 生肖狗和什么生肖相冲| 甚嚣尘上什么意思| 外阴瘙痒用什么效果好| 爱的最高境界是什么| 美洲大蠊主治什么病| 6月20日是什么日子| 腿毛旺盛是什么原因| 两个人可以玩什么游戏| 甲状腺属于什么科室| 疏风解表的意思是什么| 两小无猜是什么生肖| 高项是什么| 肤色不均匀是什么原因| d表示什么| 软组织挫伤用什么药| 造势是什么意思| 小孩为什么会细菌感染| 恶心干呕吃什么药| 乳腺导管扩张是什么意思| 腥辣食物指的是什么| 沈殿霞为什么地位高| 什么什么鼎沸| 阿华田是什么饮料| 医学P代表什么| 肝胆科属于什么科| amp是什么意思| 割包皮有什么好处和坏处| 为什么早上起来口苦| 卧室养什么花好| 牙疼吃什么药最好最有效| 支原体感染是什么引起的| 什么是津液| 脖子有痣代表什么意思| 腿抽筋缺什么| 男生吃菠萝有什么好处| 什么是优质蛋白食物| 本科毕业证是什么颜色| 出冷汗是什么原因| 一月二十五号是什么星座| 孩子急性肠胃炎吃什么药| 什么是企业年金| 骨瘤是什么病| 寂灭是什么意思| 一串什么| 我可以组什么词| 北极有什么动物| 过敏涂什么药膏| 香奶奶是什么牌子| 男人勃不起是什么原因造成的| 车加昆念什么| 肠系膜淋巴结炎吃什么药| 切除甲状腺有什么影响| 黄柏泡水喝有什么功效| 天妒英才是什么意思| 梦见别人家盖房子是什么意思| 气泡水是什么水| bdsm是什么意思| 白菜什么时候播种| 脑梗吃什么中药| 什么东西越晒越湿| 烧包是什么意思| 司空见惯什么意思| 已知晓是什么意思| 酸奶有什么营养价值| 什么情况下吃救心丸| h型高血压什么意思| 肝脏多发囊肿什么意思| 尿蛋白是什么原因造成的| 男人为什么会遗精| 家五行属性是什么| 阴宅是什么意思| 心衰吃什么食物好| 奕字五行属什么| 随诊什么意思| 两肺纹理增粗是什么意思| 冲鸡蛋水喝有什么好处| 牙龈是什么| 是什么品牌| 前位子宫是什么意思| 梦见谈恋爱很甜蜜是什么意思| 被和谐了是什么意思| 晴雨表是什么意思| 大便陶土色是什么颜色| 禾加农是什么字| 椅子像什么| 10.16是什么星座| 黑枸杞泡茶是什么颜色| 琏是什么意思| 白带发黄是什么原因| 解大便时有鲜血流出是什么原因| 难于上青天是什么意思| 孩子急性肠胃炎吃什么药| 梦见自己生二胎是什么意思| 甲醛什么味道| 遇上方知有什么意思| 家里进鸟了是什么预兆| 什么火灾不能用水扑灭| 胆固醇高吃什么好| 流产吃什么药可以堕胎| 高压氧治疗有什么作用| 什么是毛囊炎及症状图片| 大荔冬枣什么时候成熟| IB是什么| 茄子有什么功效| 枕头什么牌子好| 桥本甲状腺炎有什么症状| 打胰岛素是什么病| 处女座是什么星座| 血糖高适合喝什么酒| 月经推迟吃什么药| 12.6是什么星座| 孩子上吐下泻吃什么药| 一串什么| 取是什么意思| 自然流产是什么症状| rr是什么牌子| 什么生肖晚上不睡觉| 男人手大代表什么| 囡囡是什么意思| 猪朋狗友是什么意思| 肝风内动吃什么中成药| 人口基数是什么意思| 宫腔积液吃什么药效果最好| 一什么尾巴| 引狼入室是什么意思| 牛仔裤配什么上衣| 梦见红薯是什么意思| seiko手表是什么牌子| 马镫什么时候发明的| 隔离和防晒有什么区别| 番茄什么时候种植| 嘛哩嘛哩哄是什么意思| 腐女是什么| 失眠吃什么好睡觉| 猪肝可以钓什么鱼| 北京市副市长是什么级别| 术后吃什么营养品好| 糖精对人体有什么危害| 造影是什么手术| aq是什么| 秋葵有什么好处| 贫血喝什么茶| 归宁是什么意思| 历法是什么意思| 属兔配什么属相最好| ala是什么意思| 天空为什么是蓝色的| 胆囊壁胆固醇结晶是什么意思| 猫咪能看到什么颜色| 肾不好吃什么| 阿司匹林有什么副作用| ol什么意思| 四维什么时候做| 肿瘤切开了里面是什么| 为什么冬天会下雪| 玫瑰花泡水喝有什么好处| 胃痛吃什么| 什么的鞋子| 小孩吃什么提高免疫力| 做糖耐是检查什么| 杀鸡取卵是什么生肖| 龙眼和桂圆有什么区别| 非食健字是什么意思| 什么羽毛球拍最好| 唵嘛呢叭咪吽什么意思| g750和au750有什么区别| 卵巢早衰吃什么可以补回来| 身上痒是什么原因| 什么鸟叫声最好听| 回不到我们的从前是什么歌| 脚底起泡是什么原因| 冒虚汗是什么原因| 腺样体增生是什么意思| 小孩磨牙是什么原因引起的| 有什么国家| ph值低是什么原因| 我看见了什么| 熬夜流鼻血是什么原因| 额头出油多是什么原因| 手指关节疼痛用什么药| 舌头发白吃什么药好| 247是什么意思| 瑞舒伐他汀什么时候吃最好| 因加一笔是什么字| 中国第一个不平等条约是什么| 什么样人穿棉麻好看| 移徙是什么意思| 为什么阴道会放气| 北京什么时候最热| 我们到底什么关系| 一代明君功千秋是什么生肖| 什么是保健食品| 为什么海水是咸的| 甲减吃什么盐| 孕妇吃梨有什么好处| 间接喉镜检查能检查出什么| 百度Jump to content

圆周率选择不当?外媒:用其他数学常数取代更易学习

From Wikipedia, the free encyclopedia
百度 并且和两弹元勋邓稼先先生也是亲密挚友。

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-05 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-05.
  15. ^ "exec.library/Vacate". amigadev.elowar.com. Retrieved 2025-08-05.
[edit]

Introductions

[edit]

References

[edit]
健脾益气是什么意思 红眼病是什么原因引起的 小周天是什么意思 怀孕前三个月要注意什么 盆底肌是什么
拔牙后吃什么消炎药 什么问题 白细胞计数偏低是什么原因 2048年是什么年 毛尖茶属于什么茶
市斤是什么意思 世界上最高的高原是什么 经常流鼻涕是什么原因引起的 年兽叫什么 车加昆念什么
扭捏是什么意思 mys是什么意思 入港是什么意思 上呼吸道感染吃什么药 吃什么可以软化肝脏
空气净化器什么牌子好hcv8jop3ns5r.cn 全组副鼻窦炎什么意思hcv7jop9ns9r.cn 上市公司什么意思bysq.com 蛋白尿是什么原因引起的hcv8jop4ns9r.cn 头胀是什么原因导致的hcv7jop5ns2r.cn
玫瑰糠疹用什么药hcv9jop5ns0r.cn 泡黄芪水喝有什么好处hcv9jop4ns7r.cn 准备要孩子需要注意什么hcv9jop2ns6r.cn 黄泉是什么意思hcv8jop4ns4r.cn 脾虚什么症状hcv8jop9ns1r.cn
但愿人长久的下一句是什么hcv9jop3ns4r.cn 什么叫庚日hcv9jop3ns7r.cn 胎停是什么意思hcv7jop9ns5r.cn 猪肝有什么功效与作用hcv9jop7ns1r.cn acs是什么病hcv8jop1ns1r.cn
聪明反被聪明误是什么意思hcv8jop0ns4r.cn 老化是什么意思mmeoe.com 什么花不能浇硫酸亚铁hcv8jop3ns8r.cn 南辕北辙告诉我们什么道理hcv9jop5ns6r.cn 细菌性阴道炎吃什么药好hcv8jop5ns3r.cn
百度