Created
March 6, 2020 10:34
-
-
Save PeteGabriel/a3c365cb7fe24995fb37381ad44cfa31 to your computer and use it in GitHub Desktop.
Synchronization between pieces and results in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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