funcputNum(intChan chanint) { deferclose(intChan) // 关闭 intChan for i := 2; i <= 1000; i++ { intChan <- i // 向 intChan 发送数据 } }
funcisPrime(value int)bool { if value <= 3 { return value >= 2 } if value%2 == 0 || value%3 == 0 { returnfalse } for i := 5; i*i <= value; i += 6 { if value%i == 0 || value%(i+2) == 0 { returnfalse } } returntrue }
funcgetNum(intChan chanint, outChan chanint, wg *sync.WaitGroup) { defer wg.Done() for value := range intChan { // 通过 for-range 遍历已关闭的 intChan 中的数据 if isPrime(value) { outChan <- value // 找到符合条件的数据,发送到 outChan } } }
funcmain() { var inChannel = make(chanint, 10) // 定义缓冲区为 10 的 channel var outChannel = make(chanint, 1000) // 定义缓冲区为 1000 的 channel var wg sync.WaitGroup
go putNum(inChannel) // 已经在 putNum 中关闭了 inChannel for i := 0; i < 10; i++ { wg.Add(1) go getNum(inChannel, outChannel, &wg) } wg.Wait() close(outChannel) // 关闭 outChannel,后面才可以使用 for-range 进行遍历 for x := range outChannel { fmt.Println(x) } }
funcmain() { var wg sync.WaitGroup wg.Add(2) ach, bch := make(chanint), make(chanint)
gofunc(wg *sync.WaitGroup, a, b <-chanint) { defer wg.Done() var ( name string x int ok bool ) for { select { case x, ok = <-a: name = "a" case x, ok = <-b: name = "b" } if !ok { return } fmt.Println(name, x) } }(&wg, ach, bch) gofunc(wg *sync.WaitGroup, a, b chan<- int) { defer wg.Done() deferclose(a) deferclose(b) for i := 0; i < 10; i++ { select { case a <- i: case b <- i * 10: } } }(&wg, ach, bch) wg.Wait() }
funcmain() { done := make(chanint) data := []chanint{make(chanint, 3)}
gofunc() { deferclose(done) for i := 0; i < 10; i++ { select { case data[len(data)-1] <- i: default: data = append(data, make(chanint, 3)) // default 语句用于添加新的 channel 等. } } }() <-done // 阻塞, 直到 goroutine 执行结束 for i := 0; i < len(data); i++ { c := data[i] close(c) for x := range c { fmt.Println(x) } } }
funcadd(wg *sync.WaitGroup, x *int64) { defer wg.Done() for i := 0; i < 1000; i++ { atomic.AddInt64(x, 1) } } funcmain() { var x int64 var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go add(&wg, &x) } wg.Wait() fmt.Println(x) }