Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does static code run with multiple threads?

I was reading Threading from within a class with static and non-static methods and I am in a similar situation.

I have a static method that pulls data from a resource and creates some runtime objects based on the data.

static class Worker{
    public static MyObject DoWork(string filename){
        MyObject mo = new MyObject();

        // ... does some work

        return mo;
    }
}

The method takes awhile (in this case it is reading 5-10mb files) and returns an object.

I want to take this method and use it in a multiple thread situation so I can read multiple files at once. Design issues / guidelines aside, how would multiple threads access this code?

Let's say I have something like this...

class ThreadedWorker {
    public void Run() {
        Thread t = new Thread(OnRun);
        t.Start();
    }

    void OnRun() {
        MyObject mo = Worker.DoWork("somefilename");

        mo.WriteToConsole();
    }
}

Does the static method run for each thread, allowing for parallel execution?

like image 599
Krisc Avatar asked Mar 26 '10 15:03

Krisc


2 Answers

Yes, the method should be able to run fine in multiple threads. The only thing you should worry about is accessing the same file in multiple threads at the same time.

like image 144
Kevin Crowell Avatar answered Oct 10 '22 22:10

Kevin Crowell


You should distinguish between static methods and static fields in this case. Each call to a static method will have its own "copy" of the method and its local variables. That means that in your sample, each call will operate on its own MyObject instance, and the calls will have nothing to do with each other. This also means that there is no problem with executing them on different threads.

like image 41
Fredrik Mörk Avatar answered Oct 10 '22 21:10

Fredrik Mörk