General threading question

B

Brad Wood

As I'm studying up on threading, I'm reading about the various
mechanisms in place to serialize access to various objects. From what I
can tell, the following scenario is safe:

- Create multiple instances of a class.
- Create a thread for each instance passing it a delegate of one of the
class' methods.
- Run each thread which will:
- Modify member variables of the instance
- Read from AppSettings
- Read from a database that basically maintains static data
- Not touch any other kind of global data.

Is this safe?
 
J

Jon Skeet [C# MVP]

Brad Wood said:
As I'm studying up on threading, I'm reading about the various
mechanisms in place to serialize access to various objects. From what I
can tell, the following scenario is safe:

- Create multiple instances of a class.
- Create a thread for each instance passing it a delegate of one of the
class' methods.
- Run each thread which will:
- Modify member variables of the instance
- Read from AppSettings
- Read from a database that basically maintains static data
- Not touch any other kind of global data.

Is this safe?

Sounds like it, yes. Basically, if no thread needs to share changing
data with any other thread, you're almost certainly fine.
 
B

Brad Wood

That being the case, I can't figure out what the purpose of the
LocalDataStoreSlot is. Data stuffed into these things isn't accessible
from other threads, but if can simply use object members, etc., what's
their purpose?
 
J

Jon Skeet [C# MVP]

Brad Wood said:
That being the case, I can't figure out what the purpose of the
LocalDataStoreSlot is. Data stuffed into these things isn't accessible
from other threads, but if can simply use object members, etc., what's
their purpose?

Because you don't necessarily have a reference everywhere. For
instance, it's handy to have the current session available everywhere
in ASP.NET - so it's stored as a thread local.

Consider the thread's current culture as another example - I don't know
whether this *is* stored as a thread local, but it's semantically
equivalent.

Of course, you could always have a hashtable with the thread as the
key, and clean up dead threads every so often, but it's a lot easier to
use a threadlocal :)
 

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