Skip to content

Instantly share code, notes, and snippets.

@PeteGabriel
Created March 6, 2020 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PeteGabriel/a3c365cb7fe24995fb37381ad44cfa31 to your computer and use it in GitHub Desktop.
Save PeteGabriel/a3c365cb7fe24995fb37381ad44cfa31 to your computer and use it in GitHub Desktop.
Synchronization between pieces and results in golang
type Piece struct {
index int
length int
}
type Result struct {
index int
}
func main() {
results := make(chan Result)
var wg sync.WaitGroup
peers := []int{1,2,3,4,5,6,7,8,9,10,11,12}
for idx, p := range peers {
piece := Piece{
index: idx,
length: p,
}
wg.Add(1)
go startWorker(&wg, piece, results)
}
go func(){
wg.Wait()
close(results)
}()
for r := range results {
fmt.Printf("Result with index %d has arrived\n", r.index)
}
}
func startWorker(wg *sync.WaitGroup, p Piece, res chan<- Result){
defer wg.Done()
time.Sleep(5 * time.Second)
res <- Result{index:p.index}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment