多个线程调用同一个方法? [英] Multiple threads calling the same method?

查看:86
本文介绍了多个线程调用同一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道每个线程是否在此代码中的方法上使用它:

I wanted to know if EACH thread is using it''s on method in this code:

List<thread> threadArray= new List<thread>();
int numberOfWorkers = 10;
EventWaitHandle ewh = AutoResetEvent(false);
Queue<string> container = new Queue<string>();
object sync = new object();

for(int i = 0; i < numberOfWorkers; i++)
{
    Thread t = new Thread(Worker);
    threadArray.Add(t);
    threadArray[i].Start();
}


public void Producer(string task)
{
   lock(sync)
   {
      container.Enqueue(task);
   }
   ewh.Set();
}

public void Worker()
{
    lock(sync)
    {
       string temp = container.Dequeue();
    }

    // do some work
    // after work is complete wait...
    ewh.WaitOne();
}</string></string></thread></thread>



因此,基本上我要问的是每个线程是否正在使用它的自己的" Worker方法,或者它们(线程)都共享该单个Worker方法?



So basically what I''m asking is if each thread is using it''s "own" Worker method or are they (threads) all sharing this single Worker method?

推荐答案

每个线程将共享该方法


只有一个方法,但是有10个线程.
您需要的那条线可能就是这样:
There is only one method but there are 10 threads.
The line you need is perhaps this one:
System.Diagnostics.Trace.WriteLine(string.Format("I am in thread #{0}", System.Threading.Thread.CurrentThread.ManagedThreadId));



将此行放置在不同的位置,它将告诉您什么线程运行了什么.



Place this line in various places and it will tell you what thread run what.


您好,


线程在那里创建自己调用的方法的副本.但是决定该函数中使用的数据成员/变量的我们是在函数范围内还是在外部...例如:


Hello,


Threads create there own copy of method they call. But its us who decide the data members/variables used in that function are inside the scope of function or from outside... For eg:


Class A
{

    int inta;
    public void someOperation()
    {

    .... Code to do some operations on variable inta
    }

}



在上述情况下,线程将具有不同的函数副本,但所有函数副本使用的变量是通用的.因此您需要保持变量inta的值并发.


另一个例子:



In above case , Threads will have difference copy of function but the variable used by all copy of function is common. so you need to maintain concurrency of value for variable inta.


another example :

<pre lang="c#">
class b
{
  public voidSomeOperation()
  {
     int intb;
     .... code performing some operation on intb;
  }

}



在上述情况下,不需要维护并发性,因为将有整个函数的单独副本,并且函数正在使用局部变量.

让我知道答案是否对您有用.



In above case there isn''t any need to maintain concurrency as there will be separate copy of whole function and function is using local variable.

Let me know if answer was useful for you.


这篇关于多个线程调用同一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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