Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of buffered channels in Go?

Tags:

go

channel

I understand from this question "Golang - What is channel buffer size?" that if the channel is buffered it won't block.

c := make(chan int, 1)
c <- data1 // doesn't block
c <- data2 // blocks until another goroutine receives from the channel
c <- data3
c <- data4

But I don't understand whats the use of it. Suppose if I have 2 goroutines, 1st one will received data1 and 2nd one receives data2 then it will block till any subroutines gets free to process data3.

I don't understand what difference did it make ? It would have executed the same way without buffer. Can you explain a possible scenario where buffering is useful ?

like image 666
Rahul Prasad Avatar asked Mar 30 '14 18:03

Rahul Prasad


People also ask

What is buffered and unbuffered channels in Golang?

An unbuffered channel is used to perform synchronous communication between goroutines while a buffered channel is used for perform asynchronous communication. An unbuffered channel provides a guarantee that an exchange between two goroutines is performed at the instant the send and receive take place.

What is the difference between a buffered channel and an unbuffered channel?

When a channel is created with no capacity, it is called an unbuffered channel. In turn, a channel created with capacity is called a buffered channel. To understand what the synchronization behavior will be for any goroutine interacting with a channel, we need to know the type and state of the channel.

Does buffered channel block?

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

What are go channels used for?

Go channels are used for communicating between concurrently running functions by sending and receiving a specific element type's data. When we have numerous Goroutines running at the same time, channels are the most convenient way for them to communicate with one another.


1 Answers

A buffered channel allows the goroutine that is adding data to the buffered channel to keep running and doing things, even if the goroutines reading from the channel are starting to fall behind a little bit.

For example, you might have one goroutine that is receiving HTTP requests and you want it to be as fast as possible. However you also want it to queue up some background job, like sending an email, which could take a while. So the HTTP goroutine just parses the user's request and quickly adds the background job to the buffered channel. The other goroutines will process it when they have time. If you get a sudden surge in HTTP requests, the users will not notice any slowness in the HTTP if your buffer is big enough.

like image 60
David Grayson Avatar answered Sep 20 '22 21:09

David Grayson