go - golang channel wierd deadlock related with make -
i'm new golang , meet strange behavior of go's channel. question described following.
package main import "fmt" func main() { ch := make(chan int) fmt.println("len:", len(ch)) fmt.println("cap:", cap(ch)) fmt.println("is nil:", ch == nil) go func(ch chan int){ ch <- 233 }(ch) fmt.println(<- ch) }
when run code above, got result this:
len: 0 cap: 0 nil: false 233
the len , cap of channel ch seem wierd code still works. when run code:
package main import "fmt" func main() { ch := make(chan int) fmt.println("len:", len(ch)) fmt.println("cap:", cap(ch)) fmt.println("is nil:", ch == nil) ch <- 233 // here changes! fmt.println(<- ch) }
the result became: len: 0 cap: 0 nil: false fatal error: goroutines asleep - deadlock!
goroutine 1 [chan send]: main.main() /tmp/sandbox640280398/main.go:12 +0x340
what's more, when change second code piece following: package main
import "fmt" func main() { ch := make(chan int, 1) //here changes! fmt.println("len:", len(ch)) fmt.println("cap:", cap(ch)) fmt.println("is nil:", ch == nil) ch <- 233 fmt.println(<- ch) }
things worked again, got:
len: 0 cap: 1 nil: false 233
so, can tell me following questions:
why make(chan int) return channel zero len , zero cap still can work in first code piece?
why second code use channel in main function instead of new goroutine cause deadlock?
why add cap parameter make in third code can fix problem?
what's difference between channel(in 1st , 2nd code) nil channel?
thanks!
you can create 2 types of channels: buffered channels , unbuffered channels.
buffered channel has capacity: make(chan int, 10)
buffered channels allow send them same amount of messages capacity without being blocked.
unbuffered channels has no capacity , why sending goroutine blocked until goroutine receive it.
1. unbuffered channel. main goroutine blocked on receiving channel until new goroutine send message it.
2. because using unbuffered channel sending goroutine blocked until receive it, have no other goroutines except main one, program in deadlock.
3. because of buffered goroutine. has capacity of 1, won't problem send 1 message , receive in same goroutine. blocked if try send more 1 message it. ch <- 233; ch <- 233
- code cause deadlock.
4. did mean..., if try receive or send nil channel blocked: var ch chan int; <-ch
or var ch chan int; ch <- 1
Comments
Post a Comment