gpt4 book ai didi

go - 我想在 goroutines 之间通信并无限期地阻塞主线程

转载 作者:数据小太阳 更新时间:2023-10-29 03:44:25 25 4
gpt4 key购买 nike

我如何阻止 main func 并允许 goroutines 通过 channel 进行通信以下代码示例会抛出错误

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

package main

import (
"fmt"
"time"
)

func main() {
ch := make(chan int)

go func() {
value := <-ch
fmt.Print(value) // This never prints!
}()

go func() {
for i := 0; i < 100; i++ {
time.Sleep(100 * time.Millisecond)
ch <- i
}
}()

c := make(chan int)
<-c
}

最佳答案

我想你想打印所有值 [0:99]。然后你需要在第一个 go routine 中循环。

另外,你需要传递信号来打破循环

func main() {
ch := make(chan int)
stopProgram := make(chan bool)

go func() {
for i := 0; i < 100; i++ {
value := <-ch
fmt.Println(value)
}
// Send signal through stopProgram to stop loop
stopProgram <- true
}()

go func() {
for i := 0; i < 100; i++ {
time.Sleep(100 * time.Millisecond)
ch <- i
}
}()

// your problem will wait here until it get stop signal through channel
<-stopProgram
}

关于go - 我想在 goroutines 之间通信并无限期地阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48667676/

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