许多读者,一位作家 - 这可能避免锁定? [英] Many readers, one writer - is it possible to avoid locking?

查看:153
本文介绍了许多读者,一位作家 - 这可能避免锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个字符串在内存中的列表,以及一个多线程系统,拥有众多读者,但只是一个作家线程。

Say you have an in-memory list of strings, and a multi-threaded system, with many readers but just one writer thread.

在一般情况下,它是可以实现这种系统在C#中,不使用锁?将对执行就如何线程交互(或他们可以做什么地点的限制,当)的假设?

In general, is it possible to implement this kind of system in C#, without using a lock? Would the implementation make any assumptions about how the threads interact (or place restrictions on what they can do, when)?

推荐答案

是的。关键是要确保列表保持不变。笔者将快照主要收集,修改快照,然后发布快照变量持有引用主集合。下面的例子说明了这一点。

Yes. The trick is to make sure the list remains immutable. The writer will snapshot the main collection, modify the snapshot, and then publish the snapshot to the variable holding the reference to the main collection. The following example demonstrates this.

public class Example
{
  // This is the immutable master collection.
  volatile List<string> collection = new List<string>();

  void Writer()
  {
    var copy = new List<string>(collection); // Snapshot the collection.
    copy.Add("hello world"); // Modify the snapshot.
    collection = copy; // Publish the snapshot.
  }

  void Reader()
  {
    List<string> local = collection; // Acquire a local reference for safe reading.
    if (local.Count > 0)
    {
      DoSomething(local[0]);
    }
  }
}

有一个警告夫妇使用这种方法。

There are a couple of caveats with this approach.


  • 它只能是因为有一个单一的作家。

  • 写操作为O (n)的操作。

  • 不同的读者可以同时使用不同的版本列表。

  • 这是一个相当危险的把戏。有非常具体的原因,挥发性使用,为什么一个地方参考的读者侧等处收购了。如果你不理解这些理由,那么请不要使用该模式。有太多的可能出错。

  • 的概念,这是线程安全的语义。不,它不会抛出异常,炸毁或撕裂时空中的一个整体。但是,也有其他的方法,其中该图案可以导致问题。知道限制是什么。这不是每一种情况灵丹妙药。由于上述限制,但这样做有利于你是相当有限的情景

  • It only works because there is a single writer.
  • Writes are O(n) operations.
  • Different readers may be using different version of the list simultaneously.
  • This is a fairly dangerous trick. There are very specific reasons why volatile was used, why a local reference is acquired on the reader side, etc. If you do not understand these reasons then do not use the pattern. There is too much that can go wrong.
  • The notion that this is thread-safe is semantic. No, it will not throw exceptions, blow up, or tear a whole in spacetime. But, there are other ways in which this pattern can cause problems. Know what the limitations are. This is not a miracle cure for every situation.

。最大的问题是,操作要求的完整副本第一所以他们可能会很慢。但是,如果写操作不频繁的话,这可能是可以容忍的。

Because of the above constraints the scenarios where this would benefit you are quite limited. The biggest problem is that writes require a full copy first so they may be slow. But, if the writes are infrequent then this might be tolerable.

我形容我的回答这里以及其中一个是多作家是安全的。

I describe more patterns in my answer here as well including one that is safe for multiple writers.

这篇关于许多读者,一位作家 - 这可能避免锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆