Created
November 5, 2019 09:10
-
-
Save kjk/2f155938fdd0d264618bcd8b38b091b6 to your computer and use it in GitHub Desktop.
Essential Go : Concurrency : https://www.programming-books.io/essential/go/concurrency-16e8d8c3d77e44faaf6857a1df368ce8 (made with https://codeeval.dev)
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
// :collection Essential Go | |
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
// :show start | |
var wg sync.WaitGroup | |
func sqrtWorker(chIn chan int, chOut chan int) { | |
fmt.Printf("sqrtWorker started\n") | |
for i := range chIn { | |
sqrt := i * i | |
chOut <- sqrt | |
} | |
fmt.Printf("sqrtWorker finished\n") | |
wg.Done() | |
} | |
func main() { | |
chIn := make(chan int) | |
chOut := make(chan int) | |
for i := 0; i < 2; i++ { | |
wg.Add(1) | |
go sqrtWorker(chIn, chOut) | |
} | |
go func() { | |
chIn <- 2 | |
chIn <- 4 | |
close(chIn) | |
}() | |
go func() { | |
wg.Wait() | |
close(chOut) | |
}() | |
for sqrt := range chOut { | |
fmt.Printf("Got sqrt: %d\n", sqrt) | |
} | |
} | |
// :show end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment