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

hardPass picture hardPass · May 3, 2012 · Viewed 7.5k times · Source

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?

Answer

user11617 picture user11617 · May 3, 2012

In Go, a buffered channel is just that: a thread-safe FIFO queue so what you are trying to do is perfectly valid. You shouldn't have performance issues at all with this approach.