Skip to content

Instantly share code, notes, and snippets.

@maciej
Created November 20, 2024 12:37
Show Gist options
  • Save maciej/28dddeefe1d97c5de0c4483dcd693029 to your computer and use it in GitHub Desktop.
Save maciej/28dddeefe1d97c5de0c4483dcd693029 to your computer and use it in GitHub Desktop.
Go Inverted Worker Pool pattern

Inverted worker pool

Inverted worker thread pool pattern from Rethinking Classical Concurrency Patterns

var sem = make(chan struct{}, limit)

func start() {
    for _, task := range hugeSlice {
        sem <- struct{}{}
        go func(task Task) {
            defer func() { <-sem }()
            perform(task)
        }(task)
    }
}

func wait() {
    for n:= limit; n > 0; n-- {
        sem <- struct{}{}
    }
}

This pattern could be extended to reduce goroutine creation overhaed. Make hugeSlice a channel and have the goroutines consume from it until it's empty.

Alternatively the x/sync/semaphore can be used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment