channel
- 顺序执行两个协程
package main
import (
"fmt"
"log"
"math/rand"
"sync"
"time"
)
func main() {
//顺序执行两个协程函数
ch1 := make(chan string, 5)
go testBoringWithChannelClose("boring!", ch1)
ch2 := make(chan string, 5)
go testBoringWithChannelClose("funning!", ch2)
for b := range ch1 {
go log.Printf("You say: %s", b)
}
for b := range ch2 {
go log.Printf("You say: %s", b)
}
}
func testBoringWithChannelClose(msg string, c chan string) {
for i := 0; i < 20; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
fmt.Println(msg + "结束")
close(c)
}
- 带缓冲的channel 就像一个携程池,去执行协程任务。
package main
import (
"fmt"
"log"
"math/rand"
"sync"
"time"
)
func main() {
//限制1024个协程数执行任务
goNum1024Times()
}
// 控制1024个协程
func goNum1024Times() {
var wg sync.WaitGroup
ch := make(chan struct{}, 1024)
for i := 0; i < 20000; i++ {
wg.Add(1)
ch <- struct{}{}
go func() {
defer wg.Done()
fmt.Printf("%d\n", len(ch)) //打印通道的长度
<-ch
}()
}
wg.Wait()
}