最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺析Go語言中內存泄漏的原因與解決方法

 更新時間:2024年02月06日 10:44:34   作者:banjming  
這篇文章主要來和大家聊一聊Go語言中內存泄漏的那些事,例如內存泄漏的原因與解決方法,文中的示例代碼講解詳細,需要的小伙伴可以參考下

遵循一個約定:如果goroutine負責創(chuàng)建goroutine,它也負責確保他可以停止 goroutine

channel 泄漏

發(fā)送不接收,一般來說發(fā)送者,正常發(fā)送,接收者正常接收,這樣沒啥問題。但是一旦接收者異常,發(fā)送者會被阻塞,造成泄漏。

select case 導致協(xié)程泄漏

func leakOfMemory() {
	errChan := make(chan error) //a.
	go func() {
		time.Sleep(2 * time.Second)
		errChan <- errors.New("chan error") // b.
		fmt.Println("finish ending ")
	}()

	select {
	case <-time.After(time.Second): 
		fmt.Println("超時") //c
	case err := <-errChan: //d.
		fmt.Println("err:", err)
	}
	fmt.Println("leakOfMemory exit")
}

func TestLeakOfMemory(t *testing.T) {
	leakOfMemory()
	time.Sleep(3 * time.Second)
	fmt.Println("main exit...")
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
}

上面的代碼執(zhí)行結果:

=== RUN   TestLeakOfMemory
超時
leakOfMemory exit
main exit...
NumGoroutine: 3
--- PASS: TestLeakOfMemory (4.00s)
PASS

最開始只有兩個 goruntine ,為啥執(zhí)行后有三個 goruntine ?

由于沒有往 errChan 中發(fā)送消息,所以 d 處 會一直阻塞,1s 后 ,c 處打印超時,程序退出,此時,有個協(xié)程在 b 處往協(xié)程中塞值,但是此時外面的 goruntine 已經退出了,此時 errChan 沒有接收者,那么就會在 b處阻塞,因此協(xié)程一直沒有退出,造成了泄漏,如果有很多類似的代碼,會造成 OOM。

for range 導致的協(xié)程泄漏

看如下代碼:

func leakOfMemory_1(nums ...int) {
	out := make(chan int)
	// sender
	go func() {
		defer close(out)
		for _, n := range nums { // c.
			out <- n
			time.Sleep(time.Second)
		}
	}()

	// receiver
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()
		for n := range out { //b.
			if ctx.Err() != nil { //a.
				fmt.Println("ctx timeout ")
				return
			}
			fmt.Println(n)
		}
	}()

}

func TestLeakOfMemory(t *testing.T) {
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
	leakOfMemory_1(1, 2, 3, 4, 5, 6, 7)
	time.Sleep(3 * time.Second)
	fmt.Println("main exit...")
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
}

上述代碼執(zhí)行結果:

=== RUN   TestLeakOfMemory
NumGoroutine: 2
1
2
ctx timeout 
main exit...
NumGoroutine: 3
--- PASS: TestLeakOfMemory (3.00s)
PASS

理論上,是不是最開始只有2個goruntine ,實際上執(zhí)行完出現(xiàn)了3個gorountine, 說明 leakOfMemory_1 里面起碼有一個協(xié)程沒有退出。 因為時間到了,在 a 出,程序就準備退出了,也就是說 b 這個就退出了,沒有接收者繼續(xù)接受 chan 中的數(shù)據(jù)了,c處往chan 寫數(shù)據(jù)就阻塞了,因此協(xié)程一直沒有退出,就造成了泄漏。

如何解決上面說的協(xié)程泄漏問題?

可以加個管道通知來防止內存泄漏。

func leakOfMemory_2(done chan struct{}, nums ...int) {
	out := make(chan int)
	// sender
	go func() {
		defer close(out)
		for _, n := range nums {
			select {
			case out <- n:
			case <-done:
				return
			}
			time.Sleep(time.Second)
		}
	}()

	// receiver
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()
		for n := range out {
			if ctx.Err() != nil {
				fmt.Println("ctx timeout ")
				return
			}
			fmt.Println(n)
		}
	}()
}
func TestLeakOfMemory(t *testing.T) {
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
	done := make(chan struct{})
	defer close(done)
	leakOfMemory_2(done, 1, 2, 3, 4, 5, 6, 7)
	time.Sleep(3 * time.Second)
	done <- struct{}{}
	fmt.Println("main exit...")
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
}

代碼執(zhí)行結果:

=== RUN   TestLeakOfMemory
NumGoroutine: 2
1
2
ctx timeout 
main exit...
NumGoroutine: 2
--- PASS: TestLeakOfMemory (3.00s)
PASS

最開始是 2個 goruntine 程序結束后還2個 goruntine,沒有協(xié)程泄漏。

goruntine 中 map 并發(fā)

map 是引用類型,函數(shù)值傳值是調用,參數(shù)副本依然指向m,因為值傳遞的是引用,對于共享變量,資源并發(fā)讀寫會產生競爭,故共享資源遭受到破壞。

func TestConcurrencyMap(t *testing.T) {
	m := make(map[int]int)
	go func() {
		for {
			m[3] = 3
		}

	}()
	go func() {
		for {
			m[2] = 2
		}
	}()
	//select {}
	time.Sleep(10 * time.Second)
}

上訴代碼執(zhí)行結果:

=== RUN   TestConcurrencyMap
fatal error: concurrent map writes

goroutine 5 [running]:
runtime.throw({0x1121440?, 0x0?})
    /go/go1.18.8/src/runtime/panic.go:992 +0x71 fp=0xc000049f78 sp=0xc000049f48 pc=0x10333b1
...

用火焰圖分析下內存泄漏問題

首先,程序代碼運行前,需要加這個代碼:

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	_ "net/http/pprof"
	"runtime"
	"testing"
	"time"
)

func TestLeakOfMemory(t *testing.T) {

	//leakOfMemory()
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
	for i := 0; i < 1000; i++ {
		go leakOfMemory_1(1, 2, 3, 4, 5, 6, 7)
	}
	//done := make(chan struct{})
	//defer close(done)
	//leakOfMemory_2(done, 1, 2, 3, 4, 5, 6, 7)
	time.Sleep(3 * time.Second)
	//done <- struct{}{}
	fmt.Println("main exit...")
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())
	log.Println(http.ListenAndServe("localhost:6060", nil))
}

上面的執(zhí)行后,登陸網址 http://localhost:6060/debug/pprof/goroutine?debug=1,可以看到下面的頁面:

但是看不到圖形界面,怎么辦?

需要安裝 graphviz

在控制臺執(zhí)行如下命令

brew install graphviz # 安裝graphviz,只需要安裝一次就行了
go tool pprof -http=":8081" http://localhost:6060/debug/pprof/goroutine?debug=1

然后可以登陸網頁:http://localhost:8081/ui/ 看到下圖:

發(fā)現(xiàn)有一個程序//GoProject/main/concurrency/channel.leakOfMemory_1.func1占用 cpu 特別大. 想看下這個程序是啥?

分析協(xié)程泄漏

使用如下結果:

go tool pprof http://localhost:6060/debug/pprof/goroutine

火焰圖分析:

Total:總共采樣次數(shù),100次。

Flat:函數(shù)在樣本中處于運行狀態(tài)的次數(shù)。簡單來說就是函數(shù)出現(xiàn)在棧頂?shù)拇螖?shù),而函數(shù)在棧頂則意味著它在使用CPU。

Flat%:Flat / Total。

Sum%:自己以及所有前面的Flat%的累積值。解讀方式:表中第3行Sum% 32.4%,意思是前3個函數(shù)(運行狀態(tài))的計數(shù)占了總樣本數(shù)的32.4%

Cum:函數(shù)在樣本中出現(xiàn)的次數(shù)。只要這個函數(shù)出現(xiàn)在棧中那么就算進去,這個和Flat不同(必須是棧頂才能算進去)。也可以解讀為這個函數(shù)的調用次數(shù)。

Cum%:Cum / Total

進入控制臺,輸入 top

Type: goroutine
Time: Feb 5, 2024 at 10:02am (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 1003, 99.90% of 1004 total
Dropped 35 nodes (cum <= 5)
      flat  flat%   sum%        cum   cum%
      1003 99.90% 99.90%       1003 99.90%  runtime.gopark
         0     0% 99.90%       1000 99.60%  //GoProject/main/concurrency/channel.leakOfMemory_1.func1
         0     0% 99.90%       1000 99.60%  runtime.chansend
         0     0% 99.90%       1000 99.60%  runtime.chansend1
(pprof)

其中 其中runtime.gopark即可認為是掛起的goroutine數(shù)量。發(fā)現(xiàn)有大量協(xié)程被 runtime.gopark

然后輸入 traces runtime.gopark

(pprof) traces  runtime.gopark
Type: goroutine
Time: Feb 5, 2024 at 10:02am (CST)
-----------+-------------------------------------------------------
      1000   runtime.gopark
             runtime.chansend
             runtime.chansend1
             //GoProject/main/concurrency/channel.leakOfMemory_1.func1
-----------+-------------------------------------------------------
         1   runtime.gopark
             runtime.chanrecv
             runtime.chanrecv1
             testing.(*T).Run
             testing.runTests.func1
             testing.tRunner
             testing.runTests
             testing.(*M).Run
             main.main
             runtime.main
-----------+-------------------------------------------------------
         1   runtime.gopark
             runtime.netpollblock
             internal/poll.runtime_pollWait
             internal/poll.(*pollDesc).wait
             internal/poll.(*pollDesc).waitRead (inline)
             internal/poll.(*FD).Read
             net.(*netFD).Read
             net.(*conn).Read
             net/http.(*connReader).backgroundRead
-----------+-------------------------------------------------------
         1   runtime.gopark
             runtime.netpollblock
             internal/poll.runtime_pollWait
             internal/poll.(*pollDesc).wait
             internal/poll.(*pollDesc).waitRead (inline)
             internal/poll.(*FD).Accept
             net.(*netFD).accept
             net.(*TCPListener).accept
             net.(*TCPListener).Accept
             net/http.(*Server).Serve
             net/http.(*Server).ListenAndServe
             net/http.ListenAndServe (inline)
             //GoProject/main/concurrency/channel.TestLeakOfMemory
             testing.tRunner
-----------+-------------------------------------------------------
(pprof)

可以發(fā)現(xiàn)泄漏了 1000 個 goruntine。

然后通過調用棧,可以看到調用鏈路:

channel.leakOfMemory_1.func1->runtime.chansend1->runtime.chansend->runtime.gopark

runtime.chansend1 是阻塞的調用,協(xié)程最終被 runtime.gopark 掛起,從而導致泄漏。

然后再輸入 list GoProject/main/concurrency/channel. leakOfMemory_1.func1 可以看到如下

(pprof) list //GoProject/main/concurrency/channel.
leakOfMemory_1.func1
Total: 1004
ROUTINE ======================== //GoProject/main/concurrency/channel.leakOfMemory_1.func1 in /Users/bytedance/go/src///GoProject/main/concurrency/channel/channel_test.go
         0       1000 (flat, cum) 99.60% of Total
         .          .     62:    out := make(chan int)
         .          .     63:    // sender
         .          .     64:    go func() {
         .          .     65:        defer close(out)
         .          .     66:        for _, n := range nums {
         .       1000     67:            out <- n
         .          .     68:            time.Sleep(time.Second)
         .          .     69:        }
         .          .     70:    }()
         .          .     71:
         .          .     72:    // receiver

可以看到使用了一個非緩沖的 channel, 上面已經分析了,沒有接收者,發(fā)送者out 在寫入channel 時阻塞, 協(xié)程無法退出,因此有協(xié)程泄漏。

分析內存增長泄漏

go tool pprof http://localhost:6060/debug/pprof/heap

然后輸入 top

(pprof) top
Showing nodes accounting for 6662.08kB, 86.68% of 7686.14kB total
Showing top 10 nodes out of 24
      flat  flat%   sum%        cum   cum%
 5125.63kB 66.69% 66.69%  5125.63kB 66.69%  runtime.allocm
 1024.41kB 13.33% 80.01%  1024.41kB 13.33%  runtime.malg
  512.05kB  6.66% 86.68%   512.05kB  6.66%  internal/poll.runtime_Semacquire
         0     0% 86.68%   512.05kB  6.66%  GoProject/main/concurrency/channel.leakOfMemory_1.func2
         0     0% 86.68%   512.05kB  6.66%  fmt.Fprintln
         0     0% 86.68%   512.05kB  6.66%  fmt.Println (inline)
         0     0% 86.68%   512.05kB  6.66%  internal/poll.(*FD).Write
         0     0% 86.68%   512.05kB  6.66%  internal/poll.(*FD).writeLock (inline)
         0     0% 86.68%   512.05kB  6.66%  internal/poll.(*fdMutex).rwlock
         0     0% 86.68%   512.05kB  6.66%  os.(*File).Write
(pprof)

看著不是很大,達不到內存增長泄漏的級別。

以上就是淺析Go語言中內存泄漏的原因與解決方法的詳細內容,更多關于Go內存泄漏的資料請關注腳本之家其它相關文章!

相關文章

  • 一文讀懂go中semaphore(信號量)源碼

    一文讀懂go中semaphore(信號量)源碼

    這篇文章主要介紹了一文讀懂go中semaphore(信號量)源碼的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • go語言實現(xiàn)一個簡單的http客戶端抓取遠程url的方法

    go語言實現(xiàn)一個簡單的http客戶端抓取遠程url的方法

    這篇文章主要介紹了go語言實現(xiàn)一個簡單的http客戶端抓取遠程url的方法,實例分析了Go語言http操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-03-03
  • Go習慣用法(多值賦值短變量聲明賦值簡寫模式)基礎實例

    Go習慣用法(多值賦值短變量聲明賦值簡寫模式)基礎實例

    本文為大家介紹了Go習慣用法(多值賦值,短變量聲明和賦值,簡寫模式、多值返回函數(shù)、comma,ok 表達式、傳值規(guī)則)的基礎實例,幫大家鞏固扎實Go語言基礎
    2024-01-01
  • go語言定義零值可用的類型學習教程

    go語言定義零值可用的類型學習教程

    這篇文章主要為大家介紹了go語言定義零值可用的類型教程學習,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • Golang中Error的設計與實踐詳解

    Golang中Error的設計與實踐詳解

    這篇文章主要為大家詳細介紹了Golang中Error的設計以及是具體如何處理錯誤的相關知識,文中的示例代碼簡潔易懂,需要的小伙伴可以跟隨小編一起學習一下
    2023-08-08
  • go-zero創(chuàng)建RESTful API 服務的方法

    go-zero創(chuàng)建RESTful API 服務的方法

    文章介紹了如何使用go-zero框架和goctl工具快速創(chuàng)建RESTfulAPI服務,通過定義.api文件并使用goctl命令,可以自動生成項目結構、路由、請求和響應模型以及處理邏輯,感興趣的朋友一起看看吧
    2024-11-11
  • 分享6個Go處理字符串的技巧小結

    分享6個Go處理字符串的技巧小結

    這篇文章主要介紹了分享6個Go處理字符串的技巧小結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • Go項目的目錄結構詳解

    Go項目的目錄結構詳解

    這篇文章主要介紹了Go項目的目錄結構,對基礎目錄做了講解,對項目開發(fā)中的其它目錄也一并做了介紹,需要的朋友可以參考下
    2014-10-10
  • Go?多環(huán)境下配置管理方案(多種方案)

    Go?多環(huán)境下配置管理方案(多種方案)

    這篇文章主要介紹了Go?多環(huán)境下配置管理方案,方案一配置文件管理,方案二集中式管理配置,每種方案給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • GO中什么情況會使用變量逃逸

    GO中什么情況會使用變量逃逸

    本文主要介紹了GO中什么情況會使用變量逃逸,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02

最新評論

定南县| 阳东县| 洪江市| 中山市| 德州市| 周口市| 乌审旗| 栖霞市| 云和县| 利辛县| 开鲁县| 和田县| 枣庄市| 泾阳县| 九寨沟县| 英德市| 新乐市| 望城县| 玉门市| 龙口市| 德江县| 澄江县| 搜索| 韶关市| 甘德县| 瑞安市| 连州市| 双流县| 平阴县| 项城市| 恩平市| 丹阳市| 广灵县| 建昌县| 岢岚县| 霸州市| 建水县| 宁波市| 商南县| 乳山市| 双城市|