登录
首页 >  Golang >  Go问答

在函数中初始化通道导致 goroutine 死锁

来源:stackoverflow

时间:2024-04-17 13:54:33 119浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在函数中初始化通道导致 goroutine 死锁》,聊聊,我们一起来看看吧!

问题内容

我是 go 新手,所以我确信这是我所缺少的简单内容。我正在尝试初始化一个通道以捕获来自另一个函数的用户输入。我尝试了以下方法:

package input

const up = 1
const right = 2
const down =3
const left = 4

var inputchannel chan int

type inputreader interface {
  readnextint() int
}

func initinputchannel() chan int {
  inputchannel := make(chan int, 1)
  return inputchannel
}

func sendinput(inputreader inputreader) {
    inputchannel <- inputreader.readnextint()
}

然后我使用以下代码调用代码:

package input

import (
  "testing"
  "github.com/stretchr/testify/assert"
  "github.com/stretchr/testify/mock"
)

type mockedinputreader struct {
  mock.mock
}

func (reader mockedinputreader) readnextint() int {
  return 1
}

func testshouldsendupvaluetochannelwhenupkeypressed(t *testing.t) {
  inputreader := new(mockedinputreader)
  inputreader.on("readnextint").return(up)

  receiverchannel := sendinput(inputreader)

  actualinput := <- receiverchannel
  assert.equal(t, up, actualinput)
}

查看代码,我无法找出问题所在,所以我决定重组一些东西,因为我变得绝望了。我最终得到了以下有效的结果:

package input

const UP = 1
const RIGHT = 2
const DOWN =3
const LEFT = 4

var inputChannel chan int = make(chan int, 1)

type InputReader interface {
  ReadNextInt() int
}

func SendInput(inputReader InputReader) chan int {
    inputChannel <- inputReader.ReadNextInt()
    return inputChannel
}

虽然我很高兴它能工作,但我很困惑为什么我的第一个解决方案不起作用。当我只需要抓取一次时,我也不太热衷于为每个 sendinput 调用返回我的频道。也许 'inputchannel() chan int' getter 会更好?有什么见解吗?谢谢


解决方案


正如 thundercat 在我的问题的评论中提到的,我使用了错误的变量声明形式。所以我应该做这样的事情:

package input

const UP = 1
const RIGHT = 2
const DOWN = 3
const LEFT = 4

var inputChannel chan int

type InputReader interface {
    ReadNextInt() int
}

func InitChan() chan int {
  inputChannel = make(chan int, 1)
  return inputChannel
}

func SendInput(inputReader InputReader) {
    inputChannel <- inputReader.ReadNextInt()
}

需要注意的关键是“inputchannel = make(.....)”而不是“inputchannel := make(. ...)'就像我之前尝试过的那样。

今天关于《在函数中初始化通道导致 goroutine 死锁》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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