Threading from within a class with static and non-

2019-06-08 03:06发布

Let's say I have

class classA {

    void someMethod()
    {
    Thread a = new Thread(threadMethod);
    Thread b = new Thread(threadMethod);
    a.Start();
    b.Start();
    a.Join();
    b.Join();
    }

    void threadMethod()
    {
    int a = 0;
    a++;
    Console.Writeline(a);
    }
}

class classB {

    void someMethod()
    {
    Thread a = new Thread(threadMethod);
    Thread b = new Thread(threadMethod);
    a.Start();
    b.Start();
    a.Join();
    b.Join();
    }

    static void threadMethod()
    {
    int a = 0;
    a++;
    Console.Writeline(a);
    }
}

Assuming that in classA and classB, the contents of threadMethod have no effect to anything outside of its inner scope, does making threadMethod in classB static have any functional difference?

Also, I start two threads that use the same method in the same class. Does each method get its own stack and they are isolated from one another in both classA and classB? Does again the static really change nothing in this case?

4条回答
神经病院院长
2楼-- · 2019-06-08 03:20

Maybe you can be a little more clear. It doesn't matter if the function is declared static or not in most languages. Each thread has its own private statck.

查看更多
Deceive 欺骗
3楼-- · 2019-06-08 03:28

Methods don't have stacks, threads do. In your example threadMethod only uses local variables which are always private to the thread executing the method. It doesn't make any difference if the method is static or not as the method isn't sharing any data.

查看更多
Viruses.
4楼-- · 2019-06-08 03:32

In this case there is no functional difference. Each thread gets it's own stack

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-06-08 03:40

Each thread would get it's own stack. There is no functional difference that I can tell between the two.

The only difference (obviously) is that the static version would be unable to access member functions/variables.

查看更多
登录 后发表回答