Reputation: 6004
I am trying to work with go streams and I have a few "stupid" question.
I have done a primitive stream example with the byte limit range and here is the working code and here are my questions.
1 - why this code shows 1 and 2 at the new line? Why doesn't it show 12 at the one? Does the first peace of bytes removed from the byte-limited stream? (But how we can push the 2 number into the stream when we have already pushed the 1 number?) I just can't understand it
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch)
fmt.Println(<-ch)
}
It shows:
1
2
2 question - I have tried to play with this code to understand how it works and I have removed the byte range and I have got the deadlock error. Why does it happen? Thanks!
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox557775903/main.go:7 +0x60
The deadlock error code:
package main
import "fmt"
func main() {
ch := make(chan int)
ch <- 1
ch <- 2
fmt.Println(<-ch)
fmt.Println(<-ch)
}
Thanks for any help! Sorry for the primitive questions.
Upvotes: 0
Views: 225
Reputation: 12875
Because channel operator <-
takes only 1 element from the channel. If you want them printed together try: fmt.Println("%v%v", <-c, <-c)"
Last number in channel creation make(chan int, 2)
means channel buffer - its capacity to store items. So you can easily push 2 items to channel. But what happens if you try to push one more item? The operation would be blocked because there's no space until another goroutine will read from the channel and free space.
The same applies to all channels - unbuffeted ones get blocked at first element writing. Until some goroutine reads from the channel.
Because there's no goroutine to read, writing one locks forever. You may solve it starting a reading goroutine before.
c := make(chan int)
go func () {
fmt.Println(<-c)
fmt.Println(<-c)
}()
ch <- 1
ch <- 2
This way would not get locked but start transmitting items.
Upvotes: 1
Reputation: 353
1 - why this code shows 1 and 2 at the new line ?
Answer: because you use Println() method. If you want them on one line use Print()
2 I have tried to play with this code to understand how it works and I have removed the byte rande and I have got the deadlock error. Why it happens?
As far as the code shows, you are never firing up a concurrent reader for the channel you create. Because it is unbuffered, any writes to it, will block until someone, somewhere reads from the other end.
Upvotes: 0