-
-
Save RahulJyala7/083165d2694aeb233ba80cb1e0071c79 to your computer and use it in GitHub Desktop.
A simple implementation of a semaphore in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mutex: exclusive-member access to a resource | |
Semaphore: n-member access to a resource | |
That is, a mutex can be used to syncronize access to a counter, file, database, etc. | |
A sempahore can do the same thing but supports a fixed number of simultaneous callers. For example, I can wrap my database calls in a semaphore(3) so that my multithreaded app will hit the database with at most 3 simultaneous connections. All attempts will block until one of the three slots opens up. They make things like doing naive throttling really, really easy. | |
function Semaphore(max) { | |
var counter = 0; | |
var waiting = []; | |
var take = function() { | |
if (waiting.length > 0 && counter < max){ | |
counter++; | |
let promise = waiting.shift(); | |
promise.resolve(); | |
} | |
} | |
this.acquire = function() { | |
if(counter < max) { | |
counter++ | |
return new Promise(resolve => { | |
resolve(); | |
}); | |
} else { | |
return new Promise((resolve, err) => { | |
waiting.push({resolve: resolve, err: err}); | |
}); | |
} | |
} | |
this.release = function() { | |
counter--; | |
take(); | |
} | |
this.purge = function() { | |
let unresolved = waiting.length; | |
for (let i = 0; i < unresolved; i++) { | |
waiting[i].err('Task has been purged.'); | |
} | |
counter = 0; | |
waiting = []; | |
return unresolved; | |
} | |
} | |
// testing the semaphore | |
let sema = new Semaphore(2); | |
async function test(id) { | |
console.log('queueing task', id); | |
try { | |
await sema.acquire(); | |
console.log('running task', id); | |
setTimeout(() => { | |
sema.release(); | |
}, 2000); | |
} catch (e) { | |
console.error(id, e); | |
} | |
} | |
test(1); | |
test(2); | |
test(3); | |
test(4); | |
test(5); | |
setTimeout(() => { | |
test(10); | |
test(11); | |
test(12); | |
}, 1500); | |
setTimeout(() => { | |
test(20); | |
test(21); | |
test(22); | |
}, 2700); | |
// PURGE TEST | |
// setTimeout(() => {sema.purge();}, 2200); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment