Semaphore

세마포어

Admit a limited number of jobs and queue the rest.

···
html
<div class="v"><header><b>SEMAPHORE · 2 PERMITS</b><span id="state"></span></header><main><div class="jobs" id="jobs"></div><div class="permits" id="permits"></div></main><footer>release wakes next waiter</footer></div>
css
.v{width:min(92vw,660px);height:min(86vh,310px);box-sizing:border-box;padding:clamp(9px,2.5vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);display:flex;flex-direction:column;gap:7px;color:var(--fg);font:500 clamp(15px,3.2vmin,17px)/1.25 var(--font-sans, sans-serif)}.v header,.v footer{display:flex;justify-content:space-between;align-items:center;gap:8px;white-space:nowrap}.v header b{color:var(--accent);font-size:.9em}.v header span,.v footer{color:var(--muted);font-size:.82em}.v main{flex:1;min-height:0;position:relative;overflow:hidden}.v .mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.v .active{background:var(--accent)!important;color:var(--bg)!important;border-color:var(--accent)!important}.v .muted{opacity:.28} .jobs{height:59%;display:flex;justify-content:center;align-items:center;gap:5px}.job{width:22%;padding:11px 2px;border:1px solid var(--line);border-radius:6px;text-align:center;font:600 .85em ui-monospace,monospace}.permits{text-align:center;color:var(--accent);font:600 .85em ui-monospace,monospace}
js
let n=0;function draw(){document.getElementById("jobs").innerHTML=["A","B","C","D"].map((x,i)=>"<div class=\"job "+(i>=n&&i<n+2?"active":i<n?"muted":"")+"\">"+x+"</div>").join("");document.getElementById("permits").textContent="running: "+["A + B","B + C","C + D","D + A"][n];document.getElementById("state").textContent="2 of 2 held";n=(n+1)%4}draw();setInterval(draw,1000)

A semaphore tracks a pool of permits. A job acquires one to enter and returns it afterward so a waiting job can proceed.

Unlike a mutex, it can allow more than one concurrent holder. Failure to release permits reduces capacity or stalls the system.

When to use

Use it to cap concurrent API calls or connections.

Open as page ↗