What's the difference between unbuffered channel and buffered channel? For example, arr1 := make(chan string), arr2 := make(chan string, 10), What's the difference? Espacially when using goroutine?
test1:
func main() {
c1 := make(chan int)
for i := 0; i < 2 ; i++ {
c1 <- i+1
}
for i := 0; i < 2 ; i++ {
fmt.Println(<-c1)
}
}
test2:
func main() {
c1 := make(chan int)
for i := 0; i < 2 ; i++ {
go func(i int){c1 <- i}(i)
}
for i := 0; i < 2 ; i++ {
fmt.Println(<-c1)
}
}
Why test1 will cause deadlock and test2 won't?
test3:
func main() {
c1 := make(chan int, 2)
for i := 0; i < 2 ; i++ {
c1 <- i+2
go func(i int){c1 <- i}(i)
}
for i := 0; i < 4 ; i++ {
fmt.Println(<-c1)
}
}
Why test3 outputs "2310" rather than "2301"?
test4
func main() {
c1 := make(chan int, 4)
for i := 0; i < 4 ; i++ {
go func(i int){c1 <- i}(i)
}
for i := 0; i < 4 ; i++ {
fmt.Println(<-c1)
}
}
Why test4 outputs "3012" rather than "0123"?
for the print order.
when you use goroutine,it's hard to say which goroutine will finish first.
that's why sometime we use channel to make few goroutine in a order.
you can use more goroutine in your test4 and run it few time ,then you can see order not always the same
here a example use channel as lock
```
package main
import (
"fmt"
"time"
)
var c1 chan int
func step1() {
fmt.Println("step 1")
c1 <- 1
}
func step2() {
<-c1
fmt.Println("step 2")
}
func main() {
c1 = make(chan int)
go step2()
go step1()
time.Sleep(10)
}
```
#2
更多评论
it's like a queue.
`arr1 := make(chan string)` you can put max one member into this chan,in order to push another one ,you should pop it first!
`arr2 := make(chan string, 10)` you can push 10 member ,before you push 11th you should pop some member
the number means max n in the chan at the same time.
#1