channel 先读后写的情况是怎么处理的

package main

import (
	"fmt"
	"time"
)

func main() {

	mailbox := make(chan string, 10)
	//mailbox := make(chan string)
	mail, ok := <-mailbox
	fmt.Println(mail, ok)

	go func() {

		mailbox <- "letter"
	}()

	time.Sleep(5 * time.Second)

}
`

很多channel的例子都是先写个数据,再读数据,这样运行正常,但是实际场景中 读写的顺序是未知的,也可能是先读,后写入,但是这样会提示 fatal error: all goroutines are asleep - deadlock!

共 1 个回复


weitan

你这是个无缓冲的 channel, 读取不到数据这行代码就一直被阻塞
mail, ok := <-mailbox
后面写入的协程压根没机会执行了, 改成下面这样是不是能满足你的要求 了

func main() {

	mailbox := make(chan string, 10)
	//mailbox := make(chan string)

	go func() {
		mail, ok := <-mailbox
		fmt.Println(mail, ok)
	}()

	go func() {
		mailbox <- "letter"
	}()

	time.Sleep(5 * time.Second)

}
# 0