From 31eaa11eee95a6d3ed0e9bc33533510b4b281ed0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8B=AC=E5=AD=A4=E4=BC=B6=E4=BF=9C?= <1184662350@qq.com> Date: Sat, 7 Jan 2023 21:44:10 +0800 Subject: [PATCH] =?UTF-8?q?day10=E5=8D=8F=E7=A8=8B=20=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E7=9A=84=20channel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/study/day10Goroutines/Goroutines.go | 1 + src/study/day10Goroutines/NoCacheChannel.go | 36 +++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/study/day10Goroutines/NoCacheChannel.go 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) + +}