go channel 缓冲区最大限制_GO语言圣经学习笔记(八)Goroutines和Channels - Go语言中文社区

go channel 缓冲区最大限制_GO语言圣经学习笔记(八)Goroutines和Channels


奋斗鸭!Day97

知识点

goroutinue

基本用法

golang非常深度的简化了goroutinue的使用方法,异常简单,门槛降低很多

// goroutinue 使用非常简单go f()

Goroutines和线程的区别

  • goroutinue使用动态栈,2k开始,最大1g

  • Go的运行时包含了其自己的调度器,这个调度器使用了一些技术手段,比如m:n调度,因为其会在n个操作系统线程上多工(调度)m个goroutine

  • Go的调度器使用了一个叫做GOMAXPROCS的变量来决定会有多少个操作系统的线程同时执行Go的代码

  • goroutine没有可以被程序员获取到的身份(id)的概念

注意点

channel

基本用法
  • 发送和接收两个操作都使用

  • 在接收语句中,一个不使用接收结果的接收操作也是合法的。

  • 试图重复关闭一个channel将导致panic异常,试图关闭一个nil值的channel也将导致panic异常

  • channel分带缓存和不带缓存

ch = make(chan int)    // 不带缓存 channelch = make(chan int, 0) // 不带缓存 channelch = make(chan int, 3) // 容量为3的缓存 channelcap 为缓存,len为缓存已使用长度
  • 无缓存channels 的发送和接受会以阻塞的方式让两个goroutinue进行同步,因此,无缓存channels又称同步channels。

  • 接收者接收到数据发生在唤醒发送者goroutinue之前,此称happens before:数据需要先接收到channels中,才能被channels发送出去,即先写才能读。

  • 单向channels 限制形式如下,限制在编译期检测

func counter(out chanint) {     XXX}
  • 基于select 的多路复用

func main() {    // ...create abort channel...    fmt.Println("Commencing countdown.  Press return to abort.")    // main 结束后,tick并不会停止,goroutinue泄露    tick := time.Tick(1 * time.Second)    for countdown := 10; countdown > 0; countdown-- {        fmt.Println(countdown)        // select会等待某一个case有事件到达,然后执行对应代码块,加上default的代码(如果有的话)        select {        case             // Do nothing.        case             fmt.Println("Launch aborted!")            return        }    }    // 应该显示关闭 tick: tick.Stop()    launch()}
注意点
  • 基于已关闭的channel的发送操作会导致 panic

示例

利用goroutinue 加速统计目录下文件数目和大小的示例程序,有几点可以学习借鉴下

  • 终止程序的实现

  • 打印中间状态的实现

  • sync 包的使用

  • 信号量的实现

package mainimport (  "flag"  "fmt"  "io/ioutil"  "os"  "path/filepath"  "sync"  "time")var verbose = flag.Bool("v", false, "show verbose progress messages")func main() {  // Determine the initial directories.  flag.Parse()  roots := flag.Args()  if len(roots) == 0 {    roots = []string{"/Users/bjhl/go"}  }  // Cancel traversal when input is detected.  go func() {    os.Stdin.Read(make([]byte, 1)) // read a single byte    close(done)  }()  // Traverse each root of the file tree in parallel.  fileSizes := make(chan int64)  var n sync.WaitGroup  for _, root := range roots {    n.Add(1)    go walkDir(root, &n, fileSizes)  }  go func() {    n.Wait()    close(fileSizes)  }()  // Print the results periodically.  var tick chan time.Time  if *verbose {    tick = time.Tick(500 * time.Millisecond)  }  var fileNums, byteNums int64loop:  for {    select {    case       // Drain fileSizes to allow existing goroutines to finish.      for range fileSizes {        // Do nothing.      }      return    case size, ok :=       if !ok {        break loop // fileSizes was closed      }      fileNums++      byteNums += size    case       printDiskUsage(fileNums, byteNums)    }  }  printDiskUsage(fileNums, byteNums) // final totals}func printDiskUsage(fileNums, byteNums int64) {  fmt.Printf("%d files  %.1f GBn", fileNums, float64(byteNums)/1e9)}// walkDir recursively walks the file tree rooted at dir// and sends the size of each found file on fileSizes.func walkDir(dir string, n *sync.WaitGroup, fileSizes chanint64) {  defer n.Done()  if cancelled() {    return  }  for _, entry := range dirents(dir) {    if entry.IsDir() {      n.Add(1)      subDir := filepath.Join(dir, entry.Name())      go walkDir(subDir, n, fileSizes)    } else {      fileSizes     }  }}// sema is a counting semaphore for limiting concurrency in dirents.var sema = make(chan struct{}, 20)// dirents returns the entries of directory dir.func dirents(dir string) []os.FileInfo {  select {  case sema struct{}{}:   case     return nil // cancelled  }  defer func() { // release token  entries, err := ioutil.ReadDir(dir)  if err != nil {    fmt.Fprintf(os.Stderr, "du: %vn", err)    return nil  }  return entries}var done = make(chan struct{})func cancelled() bool {  select {  case     return true  default:    return false  }}

引用

  • 《GO语言圣经》- 第八章 Goroutinue 和 Channels

  • 《GO语言圣经》- 第九章 Goroutines和线程

  • Go 内存模型和Happens Before关系

奋斗鸭!

                                           保持长久努力,不断奋进。

                                              不忘初心,砥砺前行。

                                              相信福报,默默付出。

                                            坚持住,尽量每天一更。

欢迎大家关注我的公众号

1b091059416b0916a7142f4e95066805.png

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42545292/article/details/112099880
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-13 18:24:36
  • 阅读 ( 1235 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢