thread calling methods

  • Thread starter Thread starter Pohihihi
  • Start date Start date
P

Pohihihi

When a thread calls a method (and/or that method calls another method), are they thread safe if the first method is controlled on access?
 
Pohihihi,

If a method calls another method and only one thread can execute the first method at a time I'd say both are thread safe because only one thread executes the methods. However this is very simplistic a lot of factors get involved in a real application and it also depends on what is your definition of thread safety.
 
Pohihihi said:
When a thread calls a method (and/or that method calls another
method), are they thread safe if the first method is controlled on
access?

What do you mean, exactly? Suppose FirstMethod() calls SecondMethod().
Even if there are locks to make sure that FirstMethod() is only ever
executing in one thread at a time, another thread might call
SecondMethod() directly (without going through FirstMethod()) so you
could still have two threads executing SecondMethod() at the same time.

Does that answer your question?
 
Yes that is what I was looking for. Thanks.


Jon Skeet said:
What do you mean, exactly? Suppose FirstMethod() calls SecondMethod().
Even if there are locks to make sure that FirstMethod() is only ever
executing in one thread at a time, another thread might call
SecondMethod() directly (without going through FirstMethod()) so you
could still have two threads executing SecondMethod() at the same time.

Does that answer your question?
 
Late thought, how can I make all the methods called in a thread as thread
safe?
Putting lock while calling might not be a very good option as first thread
might wait for some other thread to process. In other words how can I manage
to get all the methods in one thread without busy waiting in case locking
threads. Any other way to do that?
 
Pohihihi said:
Late thought, how can I make all the methods called in a thread as thread
safe?
Putting lock while calling might not be a very good option as first thread
might wait for some other thread to process. In other words how can I manage
to get all the methods in one thread without busy waiting in case locking
threads. Any other way to do that?

It's very hard to give an answer without a more concrete example of
what you're after. One nice ideal to strive for is to make threads as
separate as possible, so they only need to lock for very brief periods.
Most types don't really need to be threadsafe - but their safety needs
to be documented.
 
thanks actually that gives me nice start.


Jon Skeet said:
It's very hard to give an answer without a more concrete example of
what you're after. One nice ideal to strive for is to make threads as
separate as possible, so they only need to lock for very brief periods.
Most types don't really need to be threadsafe - but their safety needs
to be documented.
 
Back
Top