Multi-threaded app and Thread Safety.

R

Robert May

I have a windows service that spawns multiple threads running a thing that
does a bunch of processing. Here's the code that spawns the threads:

m_totalThreads=Convert.ToInt32(Settings.GetSetting("ProcessorThreads"));

m_executingThreads=new Thread[m_totalThreads];

for (int i=0;i < m_totalThreads;i++)

{

ProcessManager processor=new ProcessManager();

m_executingThreads=new Thread(new ThreadStart(processor.Process));

m_executingThreads.Name=i.ToString();

m_executingThreads.Start();

}

I haven't done a lot of multi-threaded stuff in the past, so I want to make
sure that I get this right. :)

My question is the following: Because I'm creating a new instance of the
ProcessManager for each thread, will I have problems with the classes that
the process manager spawns? Basically, do I need to worry about locking
instance variables in classes called by the processes manager that runs on
each thread?

Robert
 
K

Ken Kolda

As long as the ProcessManager only invokes methods on object instances it
creates (and these instances don't share any static data), then there's no
issue. Basically, as long as the object will ever be accessed on a single
thread, there's no need for locking.

Ken
 
J

Jon Skeet [C# MVP]

Robert May said:
I have a windows service that spawns multiple threads running a thing that
does a bunch of processing. Here's the code that spawns the threads:

m_totalThreads=Convert.ToInt32(Settings.GetSetting("ProcessorThreads"));

m_executingThreads=new Thread[m_totalThreads];

for (int i=0;i < m_totalThreads;i++)

{

ProcessManager processor=new ProcessManager();

m_executingThreads=new Thread(new ThreadStart(processor.Process));

m_executingThreads.Name=i.ToString();

m_executingThreads.Start();

}

I haven't done a lot of multi-threaded stuff in the past, so I want to make
sure that I get this right. :)

My question is the following: Because I'm creating a new instance of the
ProcessManager for each thread, will I have problems with the classes that
the process manager spawns? Basically, do I need to worry about locking
instance variables in classes called by the processes manager that runs on
each thread?


It really depends on whether any of the data that they use is shared.
If two different process managers end up with references to the same
instances of other classes, you'll need to think about how that data is
shared. If they're dealing with entirely separate bits of data, you
don't need to worry.

See http://www.pobox.com/~skeet/csharp/multithreading.html for more
information. (It doesn't talk about this particular issue (yet!) but
you may find it handy anyway.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top