Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Go's buffered channel as a thread-safe queue?

Tags:

People also ask

Is Golang channel thread-safe?

in Go are built as thread-safe pool of connections that can be used by multiple goroutines concurrently as opposed to a single connection.

Is Golang a FIFO channel?

Buffered channels in Go are always FIFO. The specification clearly says: Channels act as first-in-first-out queues. If the values coming out of the channel are not FIFO, then this is a bug in the channel implementation.

Do buffered channels block?

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

What is channel buffer in Golang?

Golang provides buffered channels, which allow you to specify a fixed length of buffer capacity so one can send that number of data values at once. These channels are only blocked when the buffer is full. Likewise, the channel on the receiving end will only block when the buffer is empty.


I want to find a queue structure (a data container) whose elements must be first-in-first-out. It is important for me that the structure must be thread-safe. I'm going to use this data container as something like a task or connection pool.

I know a buffered channel is thread-safe, but I wonder if it works as FIFO, especially in a concurrent situation.

And if it is possible to use buffered channel as a thread-safe queue, do I need to worry about its efficiency?