views:

173

answers:

5

Hi,

When should I take it into consideration whether my method is thread-safe or not?

thanks,

kalem keki

+2  A: 

You need this if you know that the method might be called from several threads simultaneously (either directly or from other methods).

sharptooth
+1  A: 

If you are making web application, if you are using threads, if you are writing a library and if you might do one of those in the future, make it thread safe.

Dev er dev
+1  A: 

In C#, we have found that remoting objects created with Singleton, the object is not thread safe, so you need to ensure in your class/methods that you take this into account.

astander
+3  A: 

ask: "can data be shared across threads?"

specifically:

"can an instance be shared across threads?" "can class static data be shared across threads?"

also to determine the relation betweeen const/non-const methods:

"does a mutating method invalidate class invariants during its execution?"

one way to think about this last question is

can the copy constructor run at ANY time DURING/OVERLAPPING the execution of a mutating method and still have the constructed object be valid?

(there are cases - keeping performance statistics comes to mind immediately - where the data is just the data and if a count gets dinged [I am NOT not talking about the dinging issue here only the interaction with the read] in one interval or the next it does not matter. So the mutating(dinging) method needn't be serialized with a copying method)

Of course you also need to think about mutating method interaction with mutating methods.

pgast
A: 

There are two cases:

Your work will be in a predominantly single-threaded environment. Ask yourself "is there any chance this can be called from something multithreaded?".

Your work will be in a predominantly multi-threaded environment. Ask yourself "can I prove this will only EVER be called from a single thread? Or, slightly weaker, can I prove that it will only be called while under an exclusivity guarantee?"

If the first question yields "yes" or the second yields "no", make sure your code is safe for multiple simultaneous executions.

Vatine