当前位置:网站首页>Application scenarios of channel of go question bank · 11

Application scenarios of channel of go question bank · 11

2022-06-24 18:50:00 GolangRoadmap

*

title GOLANG ROADMAP Community

*

answer (engine)

channel It is applicable to scenarios where data flows in multiple processes , There are many practical applications :

① Task timing

For example, timeout processing :

select {
    case <-time.After(time.Second):

Timing task

select {
    case <- time.Tick(time.Second)

② Decoupling producers and consumers

Producers and consumers can be decoupled , Producers only need to go to channel send data , And consumers just go from channel Get data in .

③ Control concurrency

Take reptiles for example , Such as crawling 1w Data , Concurrent crawling is required to improve efficiency , But the concurrency should not be too large , Can pass channel To control the concurrency scale , For example, support at the same time 5 Concurrent tasks :

ch := make(chan int5)
for _, url := range urls {
  go func() {
    ch <- 1
    worker(url)
    <- ch
  }
}
原网站

版权声明
本文为[GolangRoadmap]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241731461510.html