登录
首页 >  Golang >  Go问答

golang通道内存使用是动态的吗?

来源:stackoverflow

时间:2024-03-17 20:09:27 156浏览 收藏

Go 语言中的通道是一种用于 goroutine 之间通信的机制。最近有开发者发现,通道的内存使用情况与通道输入频率密切相关,即使 goroutine 数量保持不变。开发者通过实验发现,间隔越短,内存使用量越大。

问题内容

我测试了go通道的内存使用情况,发现它与通道输入频率不同,而goroutines的数量是相同的。

如下面的代码,我创建了数千个 goroutine,它们向自己的通道生成数据并消耗来自同一通道的数据。

通过仅更改生产者的变量“interval”,通过使用命令“top”进行监控,我可以看到虚拟内存和常驻内存也发生变化。

且间隔越短,内存使用量越大。

有谁知道发生了什么吗?

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

type Session struct {
    KeepAlive chan bool
}

var count = 1024 * 8 * 4

var interval = 250 * time.Millisecond //3718.0m 3.587g   1.2m S 224.0 23.1

// var interval = 500 * time.Millisecond //2011.2m 1.923g   1.2m S 118.8 12.4

// var interval = 1 * time.Second   //1124.0m 1.059g   1.1m S  73.0  6.8

func main() {

    var gracefulStop = make(chan os.Signal, 1)
    signal.Notify(gracefulStop, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)

    for i := 0; i < count; i++ {
        go Loop()
    }

    <-gracefulStop
    fmt.Println("gracefulStop")
}

func Loop() (err error) {

    var se *Session
    se = NewSession()

    se.Serve()

    return
}

func NewSession() (s *Session) {

    fmt.Println("NewSession")

    s = &Session{

        KeepAlive: make(chan bool, 1),
    }

    return
}

func (s *Session) Serve() {

    fmt.Println("Serve")

    go s.sendLoop()

    s.readLoop()

    s.Close()

    return
}

func (s *Session) Close() {

    close(s.KeepAlive)
    fmt.Println("Close")
}

// local-------------------------------------------------------

func (s *Session) readLoop() {
    fmt.Println("readLoop")

    sec := time.Duration(1 * time.Minute)

ServerHandlerLoop:
    for {
        select {

        case alive := <-s.KeepAlive:
            if alive == false {
                break ServerHandlerLoop
            }

        case <-time.After(sec):
            fmt.Println("Timeout")
            break ServerHandlerLoop

        }
    }

    fmt.Println("readLoop EXIT")
}

func (s *Session) sendLoop() {

    for {

        s.KeepAlive <- true

        time.Sleep(interval)

    }

    s.KeepAlive <- false

    fmt.Println("ReadMessage EXIT")
}

解决方案


pprof 可以告诉你你的内存都花在哪里了。只需为 net/http/pprof 包添加导入语句,并使用 http.defaultservemux 启动 http 服务器:

import _ "net/http/pprof"

func main() {
    go func() { log.fatal(http.listenandserve(":4000", nil)) }()

    //...
}

当程序运行时,运行 pprof 工具来查看有关程序的各种统计信息。由于您关心内存使用情况,因此堆配置文件(正在使用的内存)可能是最相关的。

$ go tool pprof -top 10 http://localhost:4000/debug/pprof/heap
fetching profile over http from http://localhost:4000/debug/pprof/heap
file: foo
build id: 10
type: inuse_space
time: dec 21, 2018 at 12:52pm (cet)
showing nodes accounting for 827.57mb, 99.62% of 830.73mb total
dropped 9 nodes (cum <= 4.15mb)
      flat  flat%   sum%        cum   cum%
  778.56mb 93.72% 93.72%   796.31mb 95.86%  time.newtimer
   18.25mb  2.20% 95.92%    18.25mb  2.20%  time.sleep
   17.75mb  2.14% 98.05%    17.75mb  2.14%  time.starttimer
      11mb  1.32% 99.38%       11mb  1.32%  runtime.malg
       2mb  0.24% 99.62%   798.31mb 96.10%  main.(*session).readloop
         0     0% 99.62%   798.31mb 96.10%  main.(*session).serve
         0     0% 99.62%    18.25mb  2.20%  main.(*session).sendloop
         0     0% 99.62%   800.81mb 96.40%  main.loop
         0     0% 99.62%    11.67mb  1.40%  runtime.mstart
         0     0% 99.62%    11.67mb  1.40%  runtime.newproc.func1
         0     0% 99.62%    11.67mb  1.40%  runtime.newproc1
         0     0% 99.62%    11.67mb  1.40%  runtime.systemstack
         0     0% 99.62%   796.31mb 95.86%  time.after

不出所料,您使用 time.After 创建的大量 time.timer 几乎占据了所有正在使用的内存。

想一想:使用 250 毫秒的间隔创建计时器比使用 1 秒的间隔创建计时器快 4 倍。然而,计时器的寿命与间隔不成正比——它恒定为 60 秒。因此,在任何给定点,您的活动计时器数量都会增加 4*60=240 倍。

来自时间的文档。之后:

after 等待持续时间过去,然后在返回的通道上发送当前时间。它相当于newtimer(d).c。在计时器触发之前,垃圾收集器不会回收底层计时器。如果担心效率,请改用 newtimer,并在不再需要计时器时调用 timer.stop。

因此,为每个 readloop 创建一个计时器并重新使用它。您可以通过使用空结构值通道而不是布尔值通道来进一步减少内存使用量:

type Session struct {
    KeepAlive chan struct{}
}

func (s *Session) readLoop() {
    fmt.Println("readLoop")

    d := 1 * time.Minute
    t := time.NewTimer(d)

loop:
    for {
        select {
        case _, ok := <-s.KeepAlive:
            if !ok {
                break loop
            }

            if !t.Stop() {
                <-t.C
            }
            t.Reset(d)

        case <-t.C:
            fmt.Println("Timeout")
            break loop
        }
    }

    fmt.Println("readLoop EXIT")
}

func (s *Session) sendLoop() {
    defer close(s.KeepAlive)

    for {
        s.KeepAlive <- struct{}{}
        time.Sleep(interval)
    }
}

到这里,我们也就讲完了《golang通道内存使用是动态的吗?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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