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?
I'm pretty sure that Channels are FIFO. They are also cheap so they would be memory efficient. Beyond that without knowing the details of how you are going to use them We can't really give much more advice.
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.
In general, I would say buffered channels do not make a good concurrency-safe queue. Creating them allocates memory for the entire buffer. If your queue size varies from very small to very large during execution, you have to allocate for the worst case scenario and may be wasting a lot of memory.
来源:https://stackoverflow.com/questions/10424144/is-it-possible-to-use-gos-buffered-channel-as-a-thread-safe-queue