如何锁定在多个线程中使用的变量 [英] How to lock a variable used in multiple threads

查看:90
本文介绍了如何锁定在多个线程中使用的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里严重提出了一个问题锁定多个线程中的变量因此,为了清楚起见,我将在这里提出该问题,希望我可以正确提出.

I have asked a question badly over here Lock on a variable in multiple threads so for clarity I am going to ask it here and hope I can ask it correctly.

classA
  creates instance of classB
  has methodA that can update & uses classB's myVar
  has methodB that can update & uses classB's myVar

classB
  has a variable myVar

方法A和方法B都可以在单独的线程中运行(在main中称为新线程).如何确保这是线程安全的?

methodA and methodB can both run in separate threads (called in new threads from main). How do I ensure this is thread safe?

推荐答案

使用lock关键字来保护可由多个线程同时执行的代码.

Use the lock keyword to guard code that can be executed simultaneously by more than one thread.

public class ClassA
{
  private ClassB b = new ClassB();

  public void MethodA()
  {
    lock (b)
    {
      // Do anything you want with b here.
    }
  }

  public void MethodB()
  {
    lock (b)
    {
      // Do anything you want with b here.
    }
  }
}

请注意,lock不会保护或锁定语句中使用的对象实例,这一点很重要.相反,如果使用 same 对象实例的另一个段已经在执行,则使用该对象作为标识应阻止执行的代码段的方式.换句话说,您可以在lock语句中使用任何您喜欢的对象实例,并且仍然可以安全地访问ClassB的成员.

It is important to note that lock does not guard or lock the object instance used in the statement. Instead, the object is used as a way to identify a section of code that should be prevented from executing if another section using the same object instance is already executing. In other words, you could use any object instance you like in the lock statements and it would still be safe to access members of ClassB.

这篇关于如何锁定在多个线程中使用的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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