是什么使实例成员线程不安全与公共静态不安全? [英] What makes instance members thread-unsafe vs public static?

查看:63
本文介绍了是什么使实例成员线程不安全与公共静态不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此我们都已经在MSDN上看到了许多可用的通用对象的线程通知:

So we've all seen the Threading notification on MSDN for many available generic objects:

这种类型的公共静态(在Visual Basic中为Shared)成员是线程安全的.不保证任何实例成员都是线程安全的."

"Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

我的问题是,作为实例变量而不是公共静态变量会使它不安全吗?

My question is, what is it about being an instance variable vs a public static makes it unsafe?

推荐答案

通常这是正确的.

通常,静态方法是静态的,因为它们不依赖也不访问任何其他线程也可以访问的实例定义的数据.通常,它们(静态方法)使用的唯一变量是声明并绑定到实现该方法的类的静态内存的变量,而不是绑定到为该对象创建的对象(类的实例)的内存.静态方法不能也不可以引用或利用任何此类变量.如果方法使用绑定到特定实例的这种实例数据变量,则它不能是静态的.相反,实例方法确实访问实例的某些数据元素(属性或字段).

In general static methods are static because they are not dependant on nor do they access any instance defined data that another thread could also access. In general, the only variables they (a static method) utilizes are variables declared and tied to the static memory of the class the method is implemented in, not to the memory allocated for object -(the instance of the class) created for that object. A static method does not and cannot reference or utilize any such variable. If a method uses this kind of instance data variable, tied to a specific instance, it cannot be static. An Instance method, in contrast, does access some data element (property or field) of the instance.

如果,静态方法访问类的静态属性或字段,则它同样是非线程安全的.

If, otoh, a static method accesses a static property or field of the class, it is equally non-thread -safe.

要进行比赛,必须具备四个条件.

There are four conditions needed for a race to be possible.

  1. 第一个条件是存在可以从多个线程访问的内存位置.通常,这些位置是全局/静态变量,或者是可以从全局/静态变量访问的堆内存.
  2. 第二个条件是存在一个属性(通常称为不变量),该属性与这些共享内存位置相关联,该属性必须为true或有效,程序才能正常运行.通常,该属性需要在发生更新之前为true,以使更新正确.
  3. 第三个条件是,在实际更新的某些部分中,不变属性不成立.(在处理的某些部分暂时无效或为假).
  4. 种族竞赛必须发生的第四个也是最后一个条件是,在不变式被破坏时,另一个线程正在访问内存,从而导致不一致或不正确的行为.

这篇关于是什么使实例成员线程不安全与公共静态不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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