Skip to content

Commit

Permalink
Add worker pool
Browse files Browse the repository at this point in the history
  • Loading branch information
rubiojr committed Oct 17, 2024
1 parent 7ad3dc5 commit e9c0c8f
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions lib/pool.risor
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* A simple worker pool implementation in Risor.
*
* Usage:
*
* // Create a pool with 2 workers
* pool.new(2)
*
* // Queue up some jobs
* for range 10 {
* pool.queue(func() { time.sleep(1); print("hello") })
* }
*
* // Wait for all jobs to finish
* pool.wait()
*
*/

__workers := []
__chan := chan()
__sent := 0
__done := chan()
__finished := 0

func __worker(c) {
return func() {
for _, work := range c {
work()
__done <- nil
}
}
}

// Create a new worker pool with n workers
func new(n) {
spawn(func(){
for range __done {
__finished++
if __finished == __sent {
close(__chan)
}
}
})

for i := 0; i < n; i++ {
w := __worker(__chan)
__workers.append(spawn(func() { w() }))
}
}

// Queue a function to be executed by a worker goroutine
func queue(fn) {
__sent++
__chan <- func() {
fn()
}
}

// Wait for all jobs to finish
func wait() {
<-__chan
__workers.each(func(w) { w.wait() })
}

0 comments on commit e9c0c8f

Please sign in to comment.