Multithreading 投掷:所有goroutine都睡着了-死锁

Multithreading 投掷:所有goroutine都睡着了-死锁,multithreading,go,deadlock,channel,Multithreading,Go,Deadlock,Channel,给出以下简单的围棋程序 package main import ( "fmt" ) func total(ch chan int) { res := 0 for iter := range ch { res += iter } ch <- res } func main() { ch := make(chan int) go total(ch) ch <- 1 ch <- 2

给出以下简单的围棋程序

package main

import (
    "fmt"
)

func total(ch chan int) {
    res := 0
    for iter := range ch {
        res += iter
    }
    ch <- res
}

func main() {
    ch := make(chan int)
    go total(ch)
    ch <- 1
    ch <- 2
    ch <- 3
    fmt.Println("Total is ", <-ch)
}

谢谢

因为您从未关闭
ch
频道,所以量程循环将永远不会结束

您不能在同一频道上发回结果。一个解决方案是使用另一个

您的程序可以进行如下调整:

package main

import (
    "fmt"
)

func total(in chan int, out chan int) {
    res := 0
    for iter := range in {
        res += iter
    }
    out <- res // sends back the result
}

func main() {
    ch := make(chan int)
    rch  := make(chan int)
    go total(ch, rch)
    ch <- 1
    ch <- 2
    ch <- 3
    close (ch) // this will end the loop in the total function
    result := <- rch // waits for total to give the result
    fmt.Println("Total is ", result)
}
主程序包
进口(
“fmt”
)
func总计(成交量内、成交量外){
res:=0
对于iter:=范围在{
res+=iter
}
out这也是正确的

package main

import "fmt"

func main() {
    c := make(chan int)
    go do(c)
    c <- 1
    c <- 2
    // close(c)
    fmt.Println("Total is ", <-c)
}

func do(c chan int) {
    res := 0
    // for v := range c {
    //  res = res + v
    // }
    for i := 0; i < 2; i++ {
        res += <-c
    }
    c <- res
    fmt.Println("something")
}
主程序包
输入“fmt”
func main(){
c:=制造(成交量)
去做(c)

c与这个问题没有直接关系,但对于理解goroutines仍然很有意思:如果您添加
fmt.Println(“Exiting total”)
退出后,我几天前开始学习Go,我不明白res:=0为什么只运行一次?整个函数不应该运行3次吗?在您的示例中,只有循环运行3次。@OybekToirov整个函数只运行一次,每次在
中int
中有内容时,迭代都会进行>通道只有当您知道在
rch
通道中有多少个结果时,此功能才起作用。如果您有未知的更多工作计数,会发生什么情况?如果不使用等待组,您如何完成它?您不想在func签名中指定每个通道都是读或写的吗?这并不能回答问题这是原始程序。
package main

import "fmt"

func main() {
    c := make(chan int)
    go do(c)
    c <- 1
    c <- 2
    // close(c)
    fmt.Println("Total is ", <-c)
}

func do(c chan int) {
    res := 0
    // for v := range c {
    //  res = res + v
    // }
    for i := 0; i < 2; i++ {
        res += <-c
    }
    c <- res
    fmt.Println("something")
}