views:

86

answers:

3

I have a static class with a few methods that just take in a byte array, parses it, and returns a structure. I need to call these methods from many separate threads. Do I need a lock() or some kind of thread-safety within the methods? I can't get my head around it.

+3  A: 

If your method is reentrant you don't need any locks.

In general, you need locks whenever multiple threads access a shared resource. When the method just calculates something from its arguments without accessing any shared resource, there is nothing to lock.

dtb
by your definition, his example would *not* be re-entrant.
John Weldon
That's why I put an "If" in the beginning of my answer. From the description if his method I thought it was re-entrant, but I can't tell for sure without looking at the code.
dtb
@John Why do you think so?
Yauheni Sivukha
Thanks, that's what I needed to know.
JimDaniel
A: 

Yes, the lock prevents multiple threads accessing the same data at the same time, which would lead to inconsistent / unpredictable behaviour usually.

John Weldon
A: 

If your methods have shared resource then you need synchronize access to it. It your case there is no shared resource and therefore no need to lock anything.

Yauheni Sivukha