代码之家  ›  专栏  ›  技术社区  ›  Basit Anwer

什么是“线程安全”?

  •  10
  • Basit Anwer  · 技术社区  · 14 年前

    在许多msdn文档中,这是在线程安全标题下写的;

    “此类型的任何公共静态(在VisualBasic中共享)成员都是线程安全的。任何实例成员都不能保证是线程安全的。”

    例如; here

    有人能简单地解释一下吗? 谢谢:

    4 回复  |  直到 13 年前
        1
  •  12
  •   Jon Skeet    14 年前

    埃里克·利珀特有一个优秀的 blog post 关于这个。基本上,它本身就没有什么意义。

    就我个人而言,当我看到锅炉板时,我不太相信msdn。它并不总是意味着它所说的。例如,它说的是关于 Encoding -尽管我们都使用来自各地多个线程的编码。

    除非我有任何理由相信(我做的是 编码 )我假设可以从任何线程调用任何静态成员,而不会破坏全局状态。如果我想用 实例 来自不同线程的同一对象的成员,如果我通过锁定确保一次只有一个线程使用该对象,那么我认为这没关系。(当然,情况并不总是这样。有些物体 线程亲和度 而且非常不喜欢在多个线程中使用,即使在锁定的地方也不例外。用户界面控件就是一个明显的例子。)

    当然,如果对象被不明显地共享会变得很棘手-如果我有两个对象,每个对象共享一个对第三个对象的引用,那么我最终可能会使用前两个对象,而这两个对象独立于不同的线程,并且具有所有适当的锁定-但最终仍然会损坏第三个对象。

    如果类型 宣传自己是线程安全的,我希望它能提供一些细节。如果它是不变的,那就很容易了——您可以随意使用实例,而不必担心它们。它是部分或全部“线程安全”类型,在细节非常重要的地方是可变的。

        2
  •  5
  •   Michael Petrotta user3140870    14 年前

    您可以同时从多个线程访问该类的任何公共静态成员,而不会中断该类的状态。如果多个线程试图同时使用实例方法(那些未标记为“static”的方法)访问对象,则该对象可能已损坏。

    如果试图同时从多个线程访问类的同一实例,则类是“线程安全”的。 引起问题。

        3
  •  4
  •   cHao    14 年前

    一个“线程安全”的对象意味着,如果两个线程同时在(或非常接近)单个CPU系统上使用它,则不可能被所述访问损坏。这通常是通过获取和释放锁来实现的,这会导致瓶颈,“线程安全”也意味着如果在不需要的时候完成,那么“慢”也意味着“慢”。

    公共静态成员很可能在线程之间共享(注意,vb甚至 电话

    Instance members aren't usually thread-safe, because in the general case it'd slow things down. If you have an object you want to share between threads, therefore, you'll need to do your own synchronization/locking.

        4
  •  0
  •   Sriwantha Attanayake    13 年前

    In MSDN description of .net class HashSet, there is a part that says about the thread safety. In the case of HashSet Class, MSDN says “Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.” Of cause we all know the concept of race conditions and deadlocks, but what does Microsoft wants to say in simple English? If two threads add two values to an “instance” of a HashSet there are some situation where we can get its count as one. Of cause in this situation the HashSet object is corrupted since we now have two objects in the HashSet, yet its count shows only one. However, public static version of the HashSet will never face such a corruption even if two threads concurrently add values.