英文:
Is it possible to use Go's buffered channel as a thread-safe queue?
问题
我想找一个队列结构(一个数据容器),其元素必须是先进先出的。对我来说,这个结构必须是线程安全的很重要。我打算将这个数据容器用作类似任务或连接池的东西。
我知道缓冲通道是线程安全的,但我想知道它在并发情况下是否按照先进先出的顺序工作。
如果可以将缓冲通道用作线程安全的队列,我需要担心它的效率吗?
英文:
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?
答案1
得分: 19
在Go语言中,缓冲通道就是这样的:一个线程安全的先进先出队列,所以你正在尝试的做法是完全有效的。使用这种方法,你不应该遇到任何性能问题。
英文:
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.
答案2
得分: 5
我很确定通道是先进先出的。它们也很便宜,所以它们在内存使用上是高效的。除此之外,如果不知道你将如何使用它们的细节,我们无法给出更多建议。
英文:
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.
答案3
得分: 2
一般来说,我会说缓冲通道不适合作为一个良好的并发安全队列。创建它们会为整个缓冲区分配内存。如果在执行过程中,队列的大小从非常小变化到非常大,你必须为最坏情况分配内存,可能会浪费很多内存。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论