1. // A concurrent prime sieve
    2. package main
    3. import "fmt"
    4. // Send the sequence 2, 3, 4, ... to channel 'ch'.
    5. func Generate(ch chan<- int) {
    6. for i := 2; ; i++ {
    7. ch <- i // Send 'i' to channel 'ch'.
    8. }
    9. }
    10. // Copy the values from channel 'in' to channel 'out',
    11. // removing those divisible by 'prime'.
    12. func Filter(in <-chan int, out chan<- int, prime int) {
    13. for {
    14. i := <-in // Receive value from 'in'.
    15. if i%prime != 0 {
    16. out <- i // Send 'i' to 'out'.
    17. }
    18. }
    19. }
    20. // The prime sieve: Daisy-chain Filter processes.
    21. func main() {
    22. ch := make(chan int) // Create a new channel.
    23. go Generate(ch) // Launch Generate goroutine. 建立chan 从2开始依次填入数据,因为无缓冲, 当值被取走后才会结束阻塞
    24. for i := 0; i < 10; i++ { //重复执行10次 取前10个质数
    25. prime := <-ch //取值 第一个是2 后面chan会被替换 ,数字被过滤
    26. fmt.Println(prime)
    27. ch1 := make(chan int)
    28. go Filter(ch, ch1, prime) //过滤旧chan数据 转移到新chan (过滤掉被该质数整除的数)
    29. ch = ch1 //替换chan
    30. }
    31. }

    lALPJxuMRVVdtLHNAYbNA-8_1007_390.png
    image.png
    lALPJx8Zw_okNLrNBYDNBhI_1554_1408.png

    1. package main
    2. func main() {
    3. // create new channel of type int
    4. ch := make(chan int)
    5. // start new anonymous goroutine
    6. go func() {
    7. // send 42 to channel
    8. ch <- 42
    9. }()
    10. // read from channel
    11. <-ch
    12. }

    在 Go 中可视化并发 - 图4

    1. package main
    2. import "time"
    3. func timer(d time.Duration) <-chan int {
    4. c := make(chan int)
    5. go func() {
    6. time.Sleep(d)
    7. c <- 1
    8. }()
    9. return c
    10. }
    11. func main() {
    12. for i := 0; i < 24; i++ {
    13. c := timer(1 * time.Second)
    14. <-c
    15. }
    16. }

    在 Go 中可视化并发 - 图5

    1. package main
    2. import "time"
    3. func main() {
    4. var Ball int
    5. table := make(chan int)
    6. go player(table)
    7. go player(table)
    8. table <- Ball
    9. time.Sleep(1 * time.Second)
    10. <-table
    11. }
    12. func player(table chan int) {
    13. for {
    14. ball := <-table
    15. ball++
    16. time.Sleep(100 * time.Millisecond)
    17. table <- ball
    18. }
    19. }

    在 Go 中可视化并发 - 图6

    1. go player(table)
    2. go player(table)
    3. go player(table)

    在 Go 中可视化并发 - 图7
    参考:https://www.cloudbees.com/blog/visualizing-concurrency-go