c# - 静态类的竞争条件?

标签 c# multithreading static

假设我有一个带有静态方法的静态类。

多个线程可以同时调用这个静态方法。

在这些情况下是否存在竞争条件的可能性:

a - if the method depends only on local variables
b - if the method depends on local variables and member fields

最佳答案

Let's say I have a static class with a static method. Multiple threads can call this static method concurrently.

好的。

Is there a potential for a race condition under these circumstances: a - if the method depends only on local variables

是的,存在潜在的竞争条件。

b - if the method depends on local variables and member fields

是的,存在潜在的竞争条件。

(a) 和 (b) 的答案是更一般规则的结果,即,总是您调用任何时都可能出现竞争条件来自多个线程的任何 方法。例如,这个程序死锁:

class MyClass
{
  static MyClass() 
  {
    // Let's run the initialization on another thread!
    var thread = new System.Threading.Thread(Initialize);
    thread.Start();
    thread.Join();
  }

  static void Initialize() 
  { }

  static void Main() 
  { }
}

它没有字段,两个完全不做任何事情的方法,以及一个只能在单个线程上访问的局部变量。然而,它会立即并持续陷入僵局。 (你明白为什么了吗?有关此程序的更多信息,请参阅 http://ericlippert.com/2013/01/31/the-no-lock-deadlock/。)

如果您的静态方法不访问字段,听起来您正在寻找保证您的程序是线程安全的。 没有这样的保证。您的程序是线程安全的当且仅当您编写的程序是线程安全的。

关于c# - 静态类的竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9792163/

相关文章:

javascript - 如何理解 `JavaScript static methods are also not callable when the class is instantiated`

c# - MVC 将 PartialViewResult 渲染为字符串

c# - 在指定时间间隔后调用事件

multithreading - 如何从Parallel.For循环线程写访问字符串变量?

c++ - 为什么不将临时对象传递给另一个线程会导致未定义的行为?

java - wait() 没有捕获 notification();导致奇怪的死锁行为

oop - OOP中的静态方法

c# - 使数据库类静态化?

c# - 字母顺序不比较从左到右?

c# - Mysql数据库列数的图表