diff --git a/src/study/day10Goroutines/Goroutines.go b/src/study/day10Goroutines/Goroutines.go index 1c6dcce..89f040c 100644 --- a/src/study/day10Goroutines/Goroutines.go +++ b/src/study/day10Goroutines/Goroutines.go @@ -21,6 +21,7 @@ func main() { const n = 45 fibN := fib(n) // slow fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN) + any } func spinner(delay time.Duration) { diff --git a/src/study/day10Goroutines/NoCacheChannel.go b/src/study/day10Goroutines/NoCacheChannel.go new file mode 100644 index 0000000..aed8369 --- /dev/null +++ b/src/study/day10Goroutines/NoCacheChannel.go @@ -0,0 +1,36 @@ +package main + +import ( + "time" +) + +// 不带缓存的channel +// 无缓存的channel,发送端发送数据,必须等待接收端接收数据 +// 同样的, 接收数据,也必须等待发送端发送数据 +// 如果有一方发了数据,但是另一方没有接收,那么就会发生阻塞 +// 如果要接收数据,但是没有数据发送,那么也会发生阻塞 +func main() { + ch := make(chan int) + // 模拟发送数据 + go func() { + // 模拟耗时操作 + time.Sleep(5 * time.Second) + ch <- 1 + println("发送数据") + }() + + // 程序阻塞, 等待接受数据 + println("接收数据1", <-ch) + + // 模拟接收数据 + go func() { + // 此程序会阻塞, 因为没有数据发送 + println("接收数据2", <-ch) + }() + // 模拟耗时 + time.Sleep(3 * time.Second) + ch <- 2 + // 模拟耗时, 等待所有的goroutine执行完毕 + time.Sleep(3 * time.Second) + +}