golang的缓冲channel和无缓冲channel的区别
发布网友
发布时间:2022-04-27 02:23
我来回答
共1个回答
热心网友
时间:2022-04-20 10:46
有缓冲的
1 package main
2
3 import "fmt"
4
5 var c = make(chan int, 1)
6
7 func f() {
8
9 c <- 'c'
10
11 fmt.Println("在goroutine内")
12 }
13
14 func main() {
15 go f()
16
17 c <- 'c'
18 <-c
19 <-c
20
21 fmt.Println("外部调用")
22 }
无缓冲的
// pp
package main
import (
"fmt"
)
func writeRoutine(test_chan chan int, value int) {
test_chan <- value
}
func readRoutine(test_chan chan int) {
<-test_chan
return
}
func main() {
c := make(chan int)
x := 100
//readRoutine(c)
//go writeRoutine(c, x)
//writeRoutine(c, x)
//go readRoutine(c)
//go readRoutine(c)
//writeRoutine(c, x)
go writeRoutine(c, x)
readRoutine(c)
fmt.Println(x)
}