登录
首页 >  Golang >  Go问答

为何goroutine会停顿几分钟

来源:stackoverflow

时间:2024-03-08 12:54:26 337浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《为何goroutine会停顿几分钟》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我有一个用 go 编写的任务,用于从 aws s3 读取 .gz 文件,每个 .gz 文件的大小将为 20m

每个 goroutine 都会从 s3 下载一个 .gz 文件到本地磁盘,然后通过 gzip.newreader 逐行读取其内容。

当任务(goroutine)数量超过70时,67个goroutine将成功完成其操作。但是剩下的 goroutine 将暂停几分钟。

在暂停的那一刻,我看到cpu为100%,然后cpu会低至0.2%(4cpu,16g内存)并停留几分钟。

问题:我很困惑,为什么 goroutine 在 cpu 很低的情况下什么都不做?可能是什么原因造成的?

test results:
60 goroutines, it will finish successfully in 27 seconds;
70 goroutines, it will finish successfully in 30s;
80 goroutines, 77 of them will finish successfully in 30s, but the remaining 3 will **pause 4 minutes**, then restart and finish in 10s

代码如下:

主协程:

func main() {
      runtime.gomaxprocs(runtime.numcpu()*2)
      chs := make([]chan string, 70)
      for i:=min; i

读取对象:

func reads3obj(s3keyname, ch chan string) {
    sess, err := session.newsession(&aws.config{
              region: aws.string("x"),
              credentials: credentials.newstaticcredentials("x", "x", "")},)

    downloader := s3manager.newdownloader(sess)

    //create a zipfile to download from s3 to local
    zipfile, err := os.create(zipname)

    //download .gz file from s3
    n, err := downloader.download(zipfile, &s3.getobjectinput{
        bucket: aws.string(bucket),
        key:    aws.string(s3keyname),
    })
    //create a file reader
    filereader, err := os.open(zipfile)

    //create a gzip reader      
    gzipreader, err := gzip.newreader(filereader)

    //create a buffered reader
    buf := bufio.newreader(gzipreader)

    //read zip file line by line
    for line, isprefix, err := []byte{0}, false, error(nil); len(line) > 0 && err == nil; {
        line, isprefix, err = buf.readline()
       //insert line to es
    }
  }

编辑: 当它暂停时,打开的文件数量非常少,所以我认为打开的文件没有超过大多数,这并不重要。因为:

ll /proc/pid/fd 的输出为

zc@ip-xxx:/proc/18059/fd$ ll
total 0
dr-x------ 2 zc zc  0 Dec 26 06:50 ./
dr-xr-xr-x 9 zc zc  0 Dec 26 06:50 ../
lrwx------ 1 zc zc 64 Dec 26 06:50 0 -> /dev/pts/0
lrwx------ 1 zc zc 64 Dec 26 06:50 1 -> /dev/pts/0
lrwx------ 1 zc zc 64 Dec 26 06:50 12 -> 
/home/zc/75.gz
lrwx------ 1 zc zc 64 Dec 26 06:50 2 -> /dev/pts/0
lrwx------ 1 zc zc 64 Dec 26 06:50 21 -> 
/home/zc/78.gz
lrwx------ 1 zc zc 64 Dec 26 06:50 253 -> socket:[76054]
lrwx------ 1 zc zc 64 Dec 26 06:50 280 -> socket:[77064]
lrwx------ 1 zc zc 64 Dec 26 06:50 47 -> 
/home/zc/58.gz
lrwx------ 1 zc zc 64 Dec 26 06:50 65 -> anon_inode:[eventpoll]
lrwx------ 1 zc zc 64 Dec 26 06:50 93 -> socket:[75984]

解决方案


golang gzip 库在一个 goroutine 中读取文件,

这么大的文件长时间占用cpu 100%。请改用 pzip

用作 gzip 的替代品,交换

import "compress/gzip"

import gzip "github.com/klauspost/pgzip".

到这里,我们也就讲完了《为何goroutine会停顿几分钟》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>