C# CircularBuffer 高效实现(线程安全和非线程安全)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13275975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:02:06  来源:igfitidea点击:

CircularBuffer highly efficient implementation (both thread-safe and not thread-safe)

c#

提问by javapowered

Could someone suggest good CircularBuffer implementation? I need both "not thread-safe" and "thread-safe" versions. I expect following operations:

有人可以建议好的 CircularBuffer 实现吗?我需要“非线程安全”和“线程安全”版本。我期望以下操作:

  • ability to provide size of the buffer when creating
  • adding elements
  • iterating elements
  • removing elements while iterating
  • probably removing elements
  • 创建时提供缓冲区大小的能力
  • 添加元素
  • 迭代元素
  • 迭代时删除元素
  • 可能删除元素

I expect implementation to be highly optimized in terms of speed and used memory, average and worst times etc.

我希望在速度和使用的内存、平均和最坏时间等方面对实现进行高度优化。

I expect "not thread-safe" implementation to be extremely fast. I expect "thread-safe" implementation to be fast, probably using "lock-free code" for synchronization and it's ok to have some restrictions if this is required for speed.

我希望“非线程安全”的实现非常快。我希望“线程安全”实现很快,可能使用“无锁代码”进行同步,如果速度需要,可以有一些限制。

If buffer is too small to store new (added) element it's ok to silenty override existent element or raise exception.

如果缓冲区太小而无法存储新的(添加的)元素,则可以静默覆盖现有元素或引发异常。

Should I use disruptor.net?

我应该使用disruptor.net吗?

Adding link to a good example Disruptor.NET example

添加到一个好的示例Disruptor.NET 示例的链接

采纳答案by Servy

Not thread safe:

不是线程安全的:

System.Collections.Generic.Queue

System.Collections.Generic.Queue

Thread safe:

线程安全:

System.Collections.Concurrent.ConcurrentQueue

System.Collections.Concurrent.ConcurrentQueue

or

或者

System.Collections.Concurrent.BlockingCollection(which uses a concurrent queue by default internally)

System.Collections.Concurrent.BlockingCollection(内部默认使用并发队列)

Although technically you really shouldn't use the term "thread safe".It's simply too ambiguous. The first is not designed to be used concurrently by multiple threads, the rest are.

虽然从技术上讲你真的不应该使用术语“线程安全”。简直太模棱两可了。第一个不是设计为由多个线程并发使用,其余的是。