我想编写三个同时发送整数的并发go例程。现在,我的代码已正确编译,但是在第一次执行后,出现错误“抛出:所有goroutine都处于睡眠状态-死锁!”。我试图找到错误,但在代码逻辑中找不到任何错误。有人可以帮助我在我的代码中查找错误吗?我的代码如下。package mainimport "rand"func Routine1(command12 chan int, response12 chan int, command13 chan int, response13 chan int) { // z12 is a variable which stores the value comming from channel 2 and z13 is a variable which stores the value comming from channel 3. z12 := 200 z13 := 200 m12 := false m13 := false y := 0 for i := 0; i < 20; i++ { y = rand.Intn(100) // If y's value is not 0 then the value will be sent to routine 2 or 3 according to prime or not. // If y's value is 0 then process state (the varibles used by it means z12, z13) and channel state will be saved.[routine 1 is initiator] if y == 0 { print(z12, " z12 STATE SAVED\n") print(z13, " z13 STATE SAVED\n") // Routine 1 is initiator, it sends 0 to make other process to save the state. y = 0 command12 <- y command13 <- y // Untill routine 2 and 3 does not send 0, process 1 is on channel saving state (it's process state is already saved). // When routine 1 recives 0 from both other processes, channel is saved and routine 1 retuns to it's common routine procedure. // When routine 1 recives 0 from any other processes, saving channel bettwen them is stopped. // m12, m13 is used to mark whether 0 recived or not.
2 回答
森林海
TA贡献2011条经验 获得超2个赞
我不知道您的问题的答案,但是中的switch
语句Routine3
看起来有问题,因为它包含两个相同的case
语句(这使我感到奇怪,为什么6g不会抱怨此代码)。
一些使您的代码更清晰的建议:
正如Evan已经指出的那样,请尝试为变量提供更多描述性的名称。读取的代码
if someConditionIsMet
比容易理解if m23 == false
。通过将通用部分分解为函数来干燥代码。
删除无效代码,例如将布尔值设置为true,然后检查其是否为true或检查奇数是否等于零。
考虑使用
else
代替if <condition> {...}; if <negated condition> {...}
我建议尝试提出单元测试,以详尽地描述您的功能的预期行为。这不仅可以帮助您找到错误,还可以提高您的编码技能。根据我的经验,考虑到测试编写的代码通常比未经测试的代码更易于理解,维护和发展。
快乐黑客:)
- 2 回答
- 0 关注
- 225 浏览
添加回答
举报
0/150
提交
取消