Go编程语言代码错误

标签 go

我尝试在 GO 中编写一个简单的代码,其中两个 go 例程(发送和接收)相互发送整数。我给出下面的代码。任何人都可以帮助我为什么这个程序的输出是[无输出]。有什么愚蠢的错误吗(抱歉,我是 GO 的新手)?

package main

func Send (in1 <-chan int, out1 chan<- int) {

                i := 2 
        out1 <- i 
    print(i, "\n")
}

func Receive (in <-chan int, out chan<- int) {

        i := <-in 
        print(i, "\n")
        out <- i 
}


func main() {

       for i := 0; i < 10; i++ {
        ch1 := make(chan int)
        ch := make(chan int) 
            go Send (ch1 , ch)
        go Receive (ch , ch1)
        ch = ch1
        ch1 = ch
        }

}

最佳答案

这个怎么样:

package main

func Send (ch chan<- int) {
    for i := 0; i < 10; i++ {
      print(i, " sending\n")
      ch <- i
    }
}

func Receive (ch <-chan int) {
    for i := 0; i < 10; i++ {
        print(<-ch, " received\n")
    }
}

func main() {
   ch := make(chan int)
   go Receive(ch)
   Send(ch)
}

当我在 golang.org 上运行它时,它的输出是:

0 sending
0 received
1 sending
2 sending
1 received
2 received
3 sending
4 sending
3 received
4 received
5 sending
6 sending
5 received
6 received
7 sending
8 sending
7 received
8 received
9 sending

我不确定为什么从未收到 9。应该有一些方法可以让主线程休眠,直到 Receive goroutine 完成。此外,接收方和发送方都知道他们将发送 10 个数字是不雅的。其中一个 goroutine 应该在另一个 goroutine 完成工作时关闭。我不确定该怎么做。

编辑 1:

这是一个有两个 channel 的实现,go 例程在彼此之间来回发送整数。一个被指定为响应者,它只在收到一个 int 后才发送和 int。响应者只需将收到的 int 值加 2,然后将其发回。

package main

func Commander(commands chan int, responses chan int) {
    for i := 0; i < 10; i++ {
      print(i, " command\n")
      commands <- i
      print(<-responses, " response\n");
    }
    close(commands)
}

func Responder(commands chan int, responses chan int) {
    for {
        x, open := <-commands
        if !open {
            return;
        }
        responses <- x + 2
    }
}

func main() {
   commands := make(chan int)
   responses := make(chan int)
   go Commander(commands, responses)
   Responder(commands, responses)
}

当我在 golang.org 上运行它时的输出是:

0 command
2 response
1 command
3 response
2 command
4 response
3 command
5 response
4 command
6 response
5 command
7 response
6 command
8 response
7 command
9 response
8 command
10 response
9 command
11 response

关于Go编程语言代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229572/

相关文章:

go - 有没有办法停止使用旧版本的 go 编译 go 代码?

json - 获取Go json unmarshal中出错的字段名

go - 如何在 Go 中压缩 int(数字)

Go blue-jay/blueprint,如何在 Controller 中分配变量并在 html/模板 View 中使用它?

string - 无法在 golang 中使用 "\n"正确拆分字符串

go - 使用 crypto/ssh 和 golang 运行 iperf3

google-app-engine - golang中不同实体种类的无情祖先查询

go - 比较等于真,但是当我把它当作条件时,为什么它没有被评估为真?

go - time.Time 日复一日

go - 是什么原因导致 "panic: runtime error: invalid memory address or nil pointer dereference"?