为什么我的去频道会受阻? (僵局)

时间:2014-04-05 15:35:21

标签: concurrency go

似乎"复杂" (getC)功能被阻止。我假设一旦读取通道就会被销毁,因此我想知道如何与sC函数和getC函数共享main通道而不会陷入死锁({ {3}})

package main

func main() {

//simple function and complex function/channel

    sC := make(chan string)
    go getS(sC)

    cC := make(chan string)
    go getC(sC, cC)

//collect the functions result 

        s := <-sC
//do something with `s`. We print but we may want to use it in a `func(s)`
print(s)
//after a while we do soemthing with `c`
        c := <-cC


    print(c)
}

func getS(sC chan string) {
    s :=  " simple completed "
    sC <- s
}

func getC(sC chan string, cC chan string) {
//we do some complex stuff
  print("complex is not complicated\n")
//Now  we need the simple value so we try wait for the s channel.
    s := <-sC

    c := s + " more "
    cC <- c //send complex value
}

3 个答案:

答案 0 :(得分:0)

您不应该尝试从main函数中的sC通道获取值,因为您发送给它的唯一值是由getC函数在单独的go例程中使用的。在尝试读取sC通道主要功能块等待某事时,它永远不会结束。常规getS已完成,常规getC消耗了来自频道sC的值并已完成。 <{1}}频道中没有任何内容。

可能的解决方案是创建另一个频道sC并向其发送从s2C频道收到的值。

完整正确的代码如下所示:

sC

答案 1 :(得分:0)

我应该从getS发送s。代码

package main

import "time"

func main() {

    //simple function and complex function/channel
    sC := make(chan string)
    go getS(sC)

    cC := make(chan string)
    go getC(sC, cC)

    //collect the functions result

    s := <-sC
    //do something with `s`. We print but we may want to use it in a `func(s)`
    print(s)
    //after a while we do soemthing with `c`
    c := <-cC

    print(c)
}

func getS(sC chan string) {
    s := " simple completed \n"
    sC <- s
    print("sent s back so that main can read it too")
    sC <- s
}

func getC(sC chan string, cC chan string) {
    time.Sleep(1 * time.Second)
    //we do some complex stuff
    print("complex is not complicated\n")
    //Now  we need the simple value so we try wait for the s channel.
    s := <-sC


    c := s + " more "
    cC <- c //send complex value
}

答案 2 :(得分:0)

我认为问题在于同步。使用睡眠可以解决问题。当您在通道上发送值时,应该在另一端接收它,否则它将显示死锁错误。 包主要

import "sync"
import "time"
import "fmt"

var wg sync.WaitGroup

func main() {
    sC := make(chan string)
    wg.Add(1)
    go getS(sC)

    cC := make(chan string)
    wg.Add(1)
    go getC(sC, cC)

    time.Sleep(1 * time.Millisecond)
    select {
    case s := <-sC:
        print(s)

    case c := <-cC:
        print(c)
    }

    wg.Wait()
}
func getS(sC chan string) {
    defer wg.Done()
    s := " simple completed "
    fmt.Println(s)
    sC <- s
}

func getC(sC chan string, cC chan string) {
    defer wg.Done()
    fmt.Println("complex is not complicated\n")
    s := <-sC
    c := s + " more "
    cC <- c //send complex value
}