[Golang] Channel blocking and non-blocking usage

The following code will deadlock:

var c1 chan string = make(chan string)
func() {
	time.Sleep(time.Second*2)
	c1 <- "result 1"
}()
fmt.Println("c1 is ", <-c1)

why? Because push and pull can never happen at the same time, this is an improper use of blocking channels.

How to solve it? This can be done:

var c1 chan string = make(chan string)
go func() {
	time.Sleep(time.Second*2)
	c1 <- "result 1"
}()
fmt.Println("c1 is ", <-c1)

By running push code in another coroutine, the production and consumption of the channel can be docked at the same time, and the normal blocking usage mode is used.

It can also be like this:

var c1 chan string = make(chan string, 1)
	func() {
		time.Sleep(time.Second*2)
		c1 <- "result 1"
	}()
	fmt.Println("c1 is ", <-c1)

Add a buffer to the channel, as long as the buffer is not exhausted, everyone does not have to block.

"Do you think that adding buffer will not block? It will block when there is no data pull"-this is simple:

bid1 := make(chan int)
go AskForBid(bid1)
time.Sleep(time.Second)
select {
case gotBid := <-bid1:
	// got bid
default:
	// no bid in one second
}

This is a non-blocking pull channel

This is the pull channel with timeout:

bid1 := make(chan int)
bid2 := make(chan int)
go AskX(bid1)
go AskY(bid2)
select {
case Xbid := <-bid1:
	// xxx
case Ybid := <-bid2:
	// yyy
case <-time.After(time.Second):
	// overtime
}
Published 425 original articles · Liked 14 · Visitors 100,000+

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/105487998