gpt4 book ai didi

go - 两个软件包之间的 channel 通信陷入僵局-Golang

转载 作者:行者123 更新时间:2023-12-01 22:00:27 24 4
gpt4 key购买 nike

两个软件包之间的 channel 通信陷入僵局-Golang。
我有两个通过两个 channel 沟通的包裹。一个是主要功能,另一个具有功能。运行它时,会出现死锁。

package main

import (
functionspackage "GoEjemplos/subFolder"
"fmt"
"sync"
)

func main() {
var wg sync.WaitGroup

ChannelSendData := make(chan functionspackage.FunctionStruct, 1)
defer close(ChannelSendData)

data := functionspackage.FunctionStruct{
FieldOne: 3.56,
FieldTwo: 23,
}

ChannelSendData <- data

wg.Add(1)
go functionspackage.FunctionExt(ChannelSendData, &wg)

recibe := <-functionspackage.ChannelOutFunct

fmt.Println("channelOut: ", recibe)

close(functionspackage.ChannelOutFunct)

wg.Wait()
}

另一个包是
package functionspackage

import "sync"

type FunctionStruct struct {
FieldOne float64
FieldTwo int
}

var ChannelOutFunct chan float64

func FunctionExt(RecibeChan chan FunctionStruct, wg *sync.WaitGroup) (ChannelOutFunct chan float64) {

reciveData := <-RecibeChan

result := reciveData.FieldOne * float64(reciveData.FieldTwo)

ChannelOutFunct <- result

wg.Done()

return ChannelOutFunct
}

这是僵局。
PS C:\Go-Project\src\GoEjemplos> go run main.go
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive (nil chan)]:
main.main()
C:/Go-Project/src/GoEjemplos/main.go:32 +0x13d

goroutine 19 [chan send (nil chan)]:
GoEjemplos/subFolder.FunctionExt(0xc0000d4000, 0xc0000a2070, 0xc0000c9f18)
C:/Go-Project/src/GoEjemplos/subFolder/functionsPackage.go:19 +0x85
created by main.main
C:/Go-Project/src/GoEjemplos/main.go:30 +0x11a
exit status 2
PS C:\Go-Project\src\GoEjemplos>
您能告诉我问题出在哪里吗?
谢谢!

最佳答案

channel functionspackage.ChannelOutFunct尚未初始化,因此为nil channel 。写入零 channel 或从零 channel 读取将始终阻塞。
https://dave.cheney.net/2014/03/19/channel-axioms

关于go - 两个软件包之间的 channel 通信陷入僵局-Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63929031/

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