mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-22 23:12:15 +08:00
docs: channel
This commit is contained in:
parent
9e6e47b4c9
commit
a954d9400c
48
base/channel/example/main.go
Normal file
48
base/channel/example/main.go
Normal file
@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var wg = new(sync.WaitGroup)
|
||||
var once = new(sync.Once)
|
||||
|
||||
//consumerNum := int32
|
||||
//var consumer = atomic.N
|
||||
|
||||
func f1(ch chan int) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 100; i++ {
|
||||
ch <- i
|
||||
}
|
||||
|
||||
// 使用完必须 close 不然将导致死锁
|
||||
close(ch)
|
||||
}
|
||||
|
||||
func f2(in chan int, out chan int) {
|
||||
defer wg.Done()
|
||||
for i := range in {
|
||||
out <- i * i
|
||||
}
|
||||
|
||||
once.Do(func() {
|
||||
// 使用完必须 close 不然将导致死锁
|
||||
close(out)
|
||||
})
|
||||
}
|
||||
|
||||
func main() {
|
||||
ch := make(chan int, 20)
|
||||
ch2 := make(chan int, 5)
|
||||
wg.Add(2)
|
||||
go f1(ch)
|
||||
go f2(ch, ch2)
|
||||
|
||||
for i := range ch2 {
|
||||
fmt.Println(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
Loading…
Reference in New Issue
Block a user