通过工作线程中的多个方法访问的成员变量 [英] member variable accessed by multiple methods within worker thread

查看:52
本文介绍了通过工作线程中的多个方法访问的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个方法的工作线程,这些方法对数据结构(List< t>)执行工作.

我想知道是否要为数据损坏做好准备.示例:

I have a worker thread with multiple methods that perform work on a data structure (List<t>).

I wanted to know if I''m setting myself up for data corruption. Example:

// Worker Thread
class threadCls
{
   string[] s = new string[] {// data...};

   threadCls()
   {
   {

   void workerThread()
   {
     // code...
     // blah, blah, blah...
  
     if (condition1 == true)
     {
        method1(s);
     }

     if (condition2 == true)
     {
        method2(s);
     }
   }

   // helper methods
   void method1(string[] s)
   {
     // preform some operation
     // on s...
   }

   void method2 (string[] s)
   {
      // preform some operation
      // on s...
   }
}



基本上我想问的是,如果condition1是否为true,并且condition2也变为true,那么method1()正在执行,因此触发method2()两种方法都可以访问string [] s吗?可能导致数据损坏.

预先感谢,
-da



basically what I''m trying to ask is if condition1 is true and method1() is executing if condition2 also becomes true therefor triggering method2() could both methods be accessing string[] s? which could cause data corruption.

thanks in advance,
-da

推荐答案

否.线程一次只能执行一个方法:method1直到完成才返回.方法2同样.

如果您有两个线程使用相同的数据,那么可以.但是单个线程一次只能做一件事.
No. The thread will only execute one method at a time: method1 will not return until is finished. The same applies to method2.

If you had two threads using the same data, then yes, you could. But a single thread does a single thing at a time.


只需添加到OriginalGriffs语句中即可.

如果您确实有多个线程使用同一个数据结构实例,那么如果没有代码修改数据,那么您就可以放心了.仅使多个线程同时读取相同的数据就不会破坏它.当您只有一个线程时,尝试在遇到问题的对象中写入(修改)数据.

如果您不能正确控制对数据结构的访问,则可能最终使一个线程在另一线程的中间读取新数据或对其进行某些其他依赖而写入新数据,从而使读取线程可能处于无效状态.数据.

就像在读一首情节,当您阅读它时,情节的主题也会发生变化.
Just to add to OriginalGriffs statements...

If you DO have multiple threads using the same data structure instance, if none of the code modifies the data, then your safe. Just having multiple threads read the same data at the same time won''t corrupt it. Its when you have one thread try to write (modify) data in the object that you''ve got problems.

If you don''t control access to the data structure properly, you could end up having one thread write new data in the middle of another thread reading it or some other dependancy on it, thereby giving the reading thread a possible invalid state of the data.

It''s kind of like reading a sentance and the topic of the sentance changes while you''re reading it.


这篇关于通过工作线程中的多个方法访问的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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