多线程应用程序中的实例类成员 [英] instance class members in a multi thread App

查看:78
本文介绍了多线程应用程序中的实例类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个奇怪的问题!
我正在编写一个应用程序.我有一个名为X的类,并且有一个X数组.数组的每个成员都指向带有不同数据的X的不同时刻.我的X类具有一些功能,其中之一例如Add.
我的问题是,如果2个或更多线程想要在X的实例中调用Add,将会发生什么?
我知道我必须同步我的函数,但是我不想在类中具有静态锁,因为其他X实例随后将等待信号,因此我定义了一个非静态对象(Mutex).

1-正确吗?或还有其他解决方案!
2-谁能描述一下当多个线程想要在同一实例中调用同一函数时会发生什么!

Hi,

I have a little odd question!
I am writing an App. I have a class named X and I have an array of X. each member of array point to a different instant of X with different data. My X class has some functions and one of them for example Add.
My question is if 2 or more threads want to call Add in an instance of X what will happen?
I know I have to syncronize my function but I do not want to have a static lock in the class because other instances of X then will wait for signal, So I defined a non static object (Mutex).

1- Is it correct? Or there are some other solutions!
2- Can anyone please describe me what will happen when more than one thread want to call a same function in a same instance!

public Class X
{
  private object _Lock=new object();
  private object Var1;
  private object Var2;
  // ...
  public void Add()
  {
    lock(_Lock)
    { 
       //I am doing something related to the current instance.
       // so other instances of X  do not need
       //to wait for each other. 
    }
  }
}

推荐答案

1.您的代码是正确的.您也可以使用Monitor类及其方法EnterLeaveTryEnter代替lock语句,这将在对象被锁定的情况下进行单独处理.

2.
一个.第一个线程将使用_Lock对象
锁定实例 b.现在,它可以安全地在lock语句下面的括号之间运行代码.
C.新线程将进入方法.它将尝试锁定,但这是不可能的.因此它将等到第一个线程释放对象.
d.第一个线程将离开lock语句部分,该部分将释放锁
e.等待中的线程之一将被唤醒并锁定对象
F.它会做的工作.当结束时,其他可能的线程将再次被唤醒并能够锁定...
1. Your code is correct. You can also instead of lock statement use Monitor class and its methods Enter, Leave and TryEnter which will allow a separate handling in the case that the object is locked.

2.
a. the first thread will lock the instance using the _Lock object
b. it now can safelly run the code between parenthesis below the lock statement.
c. new thread will enter the method. It will try lock, but it''s imposible. So it will wait until the object is released by the first thread.
d. the first thread will leave lock statement section which will release the lock
e. one of waiting threads will be waken up and will lock the object
f. it will do its work. When it ends, other possible thread will again be waken up and able to lock...


这篇关于多线程应用程序中的实例类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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