Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple threads for same method on an instance on an object

I have a question. Is it possible and valid, if I have an object with a method DoSomething(), if I create multiple threads for this method, will it work and would it run as a seperate thread of its own?

E.g.

public class SomeClass
{
    public void DoSomething()
    {
        //somethings done here
    }
}

public class MainProgram
{
    public MainProgram()
    {
         InitializeComponents();
    }

    protected override OnStart(string[] args)
    {
         SomeClass sc = new SomeClass();
         Thread workerOne = new Thread(() => sc.DoSomething());
         workerOne.Start();

         Thread workerTwo = new Thread(() => sc.DoSomething());
         workerTwo.Start(); //start a new thread calling same method
    }
}

I hope that kind of explains what I mean. Would this work or cause any problems?

I am writing a program that needs to almost be realtime software, I am currently deciding whether initialising a new instance of SomeClass is better or not?

Hope someone can answer. If my question's dont make sense, please comment and I'll explain further!

Thanks,

Base33

PS The code was written specifically for the example :)

like image 831
Base33 Avatar asked Jun 11 '12 19:06

Base33


2 Answers

Each thread has a separate call stack, so yes they can both be using the same method on the same object. And indeed, if needed each thread can (via recursion) call the same method on the same instance multiple times if you really want.

However, what might trip you up is if you are using state in that object (instance or static fields, etc, and anything related from that state). You will need to ensure your access to any shared state gives full consideration (and presumably synchronisation) to multi-threaded access.

like image 154
Marc Gravell Avatar answered Sep 19 '22 09:09

Marc Gravell


Yes you can do that. You will however have to make sure that your member accesses within that method are thread safe.

If you mutate the state of the object you should either lock your reads and writes (not speaking of any particular mechanism) or verify that it's harmless to interupt the method at any given time and that the other call on a different thread will still work correctly

like image 26
Rune FS Avatar answered Sep 18 '22 09:09

Rune FS