Skip to content

Instantly share code, notes, and snippets.

@rauljordan
Created July 21, 2021 14:29
Show Gist options
  • Save rauljordan/17235f54a84253c0b58614b9114c06f6 to your computer and use it in GitHub Desktop.
Save rauljordan/17235f54a84253c0b58614b9114c06f6 to your computer and use it in GitHub Desktop.
inprogcache
package main
import (
"fmt"
"sync"
"time"
)
var stopper chan bool // Semaphore.
var listeners []chan int
func main() {
numWorkers := 5
var wg sync.WaitGroup
wg.Add(numWorkers)
// We only want a single operation to go through
// before all others block.
stopper = make(chan bool, 1)
defer close(stopper)
listeners = make([]chan int, 0, numWorkers)
// Perform 5 expensive operations concurrently!
for i := 0; i < numWorkers; i++ {
go func(w *sync.WaitGroup, workerID int) {
defer wg.Done()
resultChan := make(chan int)
defer close(resultChan)
listeners = append(listeners, resultChan)
go scheduleWork(workerID)
result := <-resultChan
fmt.Printf("Worker %d received result %d\n", workerID, result)
}(&wg, i)
}
wg.Wait()
}
func scheduleWork(workerID int) {
// Notify the stopper channel that we are doing expensive work.
stopper <- true
result := performExpensiveWork(workerID)
// Notify all workers that work is complete.
for _, ll := range listeners {
ll <- result
}
}
func performExpensiveWork(workerID int) int {
fmt.Printf("Worker %d: Doing expensive work\n", workerID)
time.Sleep(time.Second)
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment