Skip to content

Instantly share code, notes, and snippets.

@thesephist
Created December 23, 2019 15:31
Show Gist options
  • Save thesephist/d4d3828b99ec2b3bbe542785ec8a2d7b to your computer and use it in GitHub Desktop.
Save thesephist/d4d3828b99ec2b3bbe542785ec8a2d7b to your computer and use it in GitHub Desktop.
Concurrent asynchronous queue in Ink
` concurrent task queue `
std := load('std')
log := std.log
each := std.each
range := std.range
new := maxConcurrency => (
s := {
idx: 0 ` pointer to next task `
tasks: []
running: 0
}
doNext := cb => (
t := s.tasks.(s.idx)
s.idx := s.idx + 1
t :: {
() -> cb()
_ -> t(cb)
}
)
runFromQueue := () => s.running :: {
maxConcurrency -> ()
_ -> (
s.running := s.running + 1
run := () => s.tasks.(s.idx) :: {
() -> (
s.running := s.running - 1
s.running :: {
0 -> (
` reset queue state, in case of reuse `
s.idx := 0
s.tasks := []
)
}
)
_ -> doNext(run)
}
run()
)
}
add := t => (
s.tasks.len(s.tasks) := t
runFromQueue()
)
{
add: add
}
)
` test `
q := new(5)
each(range(0, 42, 1), n => (
(q.add)(cb => (
log(n)
wait(0.5 + rand(), () => cb())
))
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment