gpt4 book ai didi

去 channel 准备

转载 作者:数据小太阳 更新时间:2023-10-29 03:45:46 30 4
gpt4 key购买 nike

我想了解 Go 中的 channel 。我读过默认情况下发送和接收 block ,直到发送方和接收方都准备好。但是我们如何确定发送方和接收方的准备情况。

例如在下面的代码中

package main

import "fmt"

func main() {
ch := make(chan int)
ch <- 1

fmt.Println(<-ch)
}

程序将卡在 channel 发送操作上,永远等待有人读取值。即使我们在 println 语句中有一个接收操作,它也会以死锁结束。

但是对于下面的程序

package main

import "fmt"

func main() {
ch := make(chan int)

go func () {
ch <- 1
}()

fmt.Println(<-ch)
}

整数从go例程成功传递到主程序。是什么让这个计划奏效?为什么第二个有效但第一个无效? go routine 会造成一些差异吗?

最佳答案

让我们逐步完成第一个程序:

// My notes here
ch := make(chan int) // make a new int channel
ch <- 1 // block until we can send to that channel
// keep blocking
// keep blocking
// still waiting for a receiver
// no reason to stop blocking yet...

// this line is never reached, because it blocks above forever.
fmt.Println(<-ch)

第二个程序将发送拆分到它自己的执行行中,所以现在我们有:

ch := make(chan int)  // make a new int channel

go func () { // start a new line of execution
ch <- 1 // block this second execution thread until we can send to that channel
}()

fmt.Println(<-ch) // block the main line of execution until we can read from that channel

由于这两条执行线可以独立工作,主线可以下到 fmt.Println 并尝试从 channel 接收。第二个线程将等待发送直到发送完毕。

关于去 channel 准备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261497/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com