【问题标题】:Does Concurrent substructures needs to be Concurrent?并发子结构是否需要并发?
【发布时间】:2015-09-04 07:01:06
【问题描述】:

在多线程应用程序中,我必须实现 ConcurrentDictionary<string,Queue<MyClass>>; 队列是否需要为ConcurrentQueue?有必要吗?我会将元素全部出列在同一个线程中,所以我认为不会。我对吗? 编辑:我没有提到我在不同的线程中排队,所以我认为正确的结构将是 Dictionary<string,ConcurrentQueue<MyClass>>。字典键仅在启动时编辑

【问题讨论】:

  • 入队怎么样?在您放入字典中的Queue<MyClass> 上是否会有超过 1 个线程同时运行?
  • 只有在有并发修改和读取操作的情况下,字典才必须是并发的。你的情况是这样吗?
  • 就我而言,我有一个线程来填充字典并将新数据排入子队列;然后是多个线程使数据出队,但仅限于选定的键。
  • mmmm 可能我正在做与我应该做的相反的事情:) 也许使用 Dictionary> 会更好吗?应用程序启动时只修改一次字典键
  • @Andrew Cattaneo:是的,应该反过来。

标签: c# multithreading data-structures concurrency


【解决方案1】:

如果您只更改传递给并发字典的AddOrUpdate() 调用的updateValueFactory 委托中的队列,那么您保证Queue 对象一次只能由一个线程访问,所以是的这种情况下你不需要使用ConcurrentQueue

例如,下面的代码将允许Enqueue()Dequeue() 随时​​被许多不同的线程调用,并且将防止ConcurrentDictionary 中的任何单个Queue 对象被多个不同的线程访问一次线程:

    private static ConcurrentDictionary<string, Queue<string>> dict;

    public static void Main()
    {
        dict = new ConcurrentDictionary<string, Queue<string>>();
    }

    // If I do this on one thread...
    private static void Enqueue(string key, string value)
    {
        dict.AddOrUpdate(
            key,
            k => new Queue<string>(new[] { value }),
            (k, q) =>
                {
                    q.Enqueue(value);
                    return q;
                });
    }

    // And I do this on another thread...
    private static string Dequeue(string key)
    {
        string result = null;
        dict.AddOrUpdate(
            "key",
            k => new Queue<string>(),
            (k, q) =>
                {
                    result = q.Dequeue();
                    return q;
                });

        return result;
    }

【讨论】:

  • 使用AddOrUpdate 进行出队?这对我来说似乎很奇怪。
猜你喜欢
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2023-03-27
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
相关资源
最近更新 更多