I\'m working on creating a call back function for an ASP.NET cache item removal event.
The documentation says I should call a method on an object or calls I know wil
No, addOne is thread-safe here - it only uses local variables. Here's an example which wouldn't be thread-safe:
class BadCounter
{
private static int counter;
public static int Increment()
{
int temp = counter;
temp++;
counter = temp;
return counter;
}
}
Here, two threads could both call Increment at the same time, and end up only incrementing once.
(Using return ++counter;
would be just as bad, by the way - the above is a more explicit version of the same thing. I expanded it so it would be more obviously wrong.)
The details of what is and isn't thread-safe can be quite tricky, but in general if you're not mutating any state (other than what was passed into you, anyway - bit of a grey area there) then it's usually okay.
The reason that 'foo' and 'someNumber' are safe in your example is that they reside on the stack, and each thread has their own stack and so are not shared.
As soon as data has the potential to be shared, for example, being global or sharing pointers to objects, then you could have conflicts and may need to use locks of some sort.
In the above example no.
Thread safety is mainly to do with stored state. You can make the above example non thread safe by doing this:
static int myInt;
static int addOne(int someNumber){
myInt = someNumber;
return myInt +1;
}
This will mean that due to context switching thread 1 might get to the call myInt = someNumber and then context switch, lets say thread 1 just set it to 5. Then imagine that thread 2 comes in and uses 6 and returns 7. Then when thread 1 wakes up again it will have 6 in myInt instead of the 5 that it was using and return 7 instead of the expected 6. :O
foo
is not shared between concurrent or sequential invocations, so addOne
is thread-safe.
Anywhere, thread safe means that you don't have two or more threads colliding when you are accessing a resource. Usually static varaiables --- in languages like C#, VB.NET and Java --- made your code thread unsafe.
In Java exists the synchronized keyword. But in .NET you get the assembly option/directive:
class Foo
{
[MethodImpl(MethodImplOptions.Synchronized)]
public void Bar(object obj)
{
// do something...
}
}
Examples of non thread safe classes should be singletons, depending on how is this pattern coded. Usually it must implement a synchronized instance creator.
If you don't want a synchronized method, you can try locking method, such as spin-lock.