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"?
有疑问加站长微信联系(非本文作者)