gpt4 book ai didi

go - 为什么所有的 goroutines 都在 sleep - 僵局。识别瓶颈

转载 作者:IT王子 更新时间:2023-10-29 00:49:42 25 4
gpt4 key购买 nike

package main

import (
"fmt"
"runtime"
"sync"
"time"
)

func main() {
intInputChan := make(chan int, 50)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go worker(intInputChan, wg)
}
for i := 1; i < 51; i++ {
fmt.Printf("Inputs. %d \n", i)
intInputChan <- i
}
close(intInputChan)
wg.Wait()
fmt.Println("Existing Main App... ")
panic("---------------")
}

func worker(input chan int, wg sync.WaitGroup) {
defer func() {
fmt.Println("Executing defer..")
wg.Done()
}()

for {
select {
case intVal, ok := <-input:
time.Sleep(100 * time.Millisecond)
if !ok {
input = nil
return
}
fmt.Printf("%d %v\n", intVal, ok)

default:
runtime.Gosched()
}
}

}

抛出的错误是。

fatal error :所有 goroutines 都睡着了 - 死锁!

goroutine 1 [semacquire]:同步。(* WaitGroup )。等待(0xc082004600) c:/go/src/sync/waitgroup.go:132 +0x170主.main() E:/Go/go_projects/go/src/Test.go:22 +0x21a

最佳答案

我刚刚尝试了它 ( playground ) 并传递了一个 wg *sync.WaitGroup 并且它有效。

传递 sync.WaitGroup 意味着传递 sync.WaitGroup 的副本(按值传递):goroutine 提到 Done() 到一个不同的 sync.WaitGroup

var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go worker(intInputChan, &wg)
}

注意 &wg:您正在按值传递指向原始 sync.WaitGroup 的指针,供 goroutine 使用。

关于go - 为什么所有的 goroutines 都在 sleep - 僵局。识别瓶颈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com