Simple Threading Question

R

Ryan Pedersen

I have a small program that executes a single very long running
background thread today.

The scope of all variables in the method that is running in this
thread today are all local to the method. The method doesn't do
anything outside of its local scope.

My question... can I start up a 2nd (3rd, and 4th and so on) thread
running the same method? Is that safe?

Todays code (abridged edition):

Thread t1 = new Thread(new ThreadStart(DoWork));
t1.Start();

public void DoWork()
{
//... do lots of work here...
}


I would like to change the code to...

Thread t1 = new Thread(new ThreadStart(DoWork));
t1.Start();

Thread t2 = new Thread(new ThreadStart(DoWork));
t2.Start();

public void DoWork()
{
//... do lots of work here...
}


Looking at this I know that it is VERY simple and I would suspect that
it would work but why? Can you explain why this works, if it does?
 
J

Jon Skeet [C# MVP]

Ryan Pedersen said:
I have a small program that executes a single very long running
background thread today.

The scope of all variables in the method that is running in this
thread today are all local to the method. The method doesn't do
anything outside of its local scope.

My question... can I start up a 2nd (3rd, and 4th and so on) thread
running the same method? Is that safe?

Yup, that's absolutely fine.
Looking at this I know that it is VERY simple and I would suspect that
it would work but why? Can you explain why this works, if it does?

It works because each thread has a different stack - the two threads
won't interfere with each other, because they have separate local
variables.
 
R

Ryan Pedersen

Thanks Jon!

I have a solid understanding of stack and heap and I never new that
each new thread got its own stack. That really opens up the issue a
lot!

It does leave me with another question though.

Say that I have two threads running and they both read a instance
field to check if they are supposed to stop or not. How can the two
threads read that class variable if they have there own stacks?

First is this "thread safe"? If not why and is it close enough? Is
there such a thing as closed enough to being thread safe?

public class MyMainClass
{
private bool stopThreads = false;

public MyMainClass
{
Thread t1 = new Thread(new ThreadStart(DoWork));
t1.Start();

Thread t2 = new Thread(new ThreadStart(DoWork));
t2.Start();
}

private void DoWork()
{
// is accessing the class variable here "thread safe"
// and why or why not? If the thread that is running
// this method has its own stack how does it know
// where to find the stopThreads data in the heap?
// did the stack get copied when the thread started?
while (!this.stopThreads)
{
// do a lot of work here
}
}
}
 

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