Created
July 15, 2013 23:35
-
-
Save mnutt/6004468 to your computer and use it in GitHub Desktop.
Simple node.js concurrency limiter
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
# Limits concurrency to @limit requests at any given time. | |
# | |
# Every time limiter.run() is called, concurrent load is incremented by one and | |
# the function you pass into it is called with a single argument of the 'done' | |
# function. When your work is complete, call the 'done' function and the | |
# concurrent load will be decremented by one. | |
# | |
# Usage: | |
# | |
# ConcurrencyLimiter = require('limiter') | |
# limiter = new ConcurrencyLimiter(10) | |
# | |
# limiter.run (done) -> | |
# fnThatTakesALongTime (result) -> | |
# console.log result | |
# done() | |
# | |
# Only 10 fnThatTakesALongTime functions will be running at any given time. The | |
# rest will be queued and run asynchronously. | |
class ConcurrencyLimiter | |
constructor: (@limit) -> | |
@count = 0 | |
@queue = [] | |
run: (cb) -> | |
if @count <= @limit | |
@count += 1 | |
console.log {count: @count, queue: @queue.length} | |
cb @done | |
else | |
@queue.push cb | |
done: => | |
@count -= 1 | |
@run(@queue.shift()) if @queue.length | |
module.exports = ConcurrencyLimiter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment