469,647 Members | 1,813 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,647 developers. It's quick & easy.

static methods and thread safety

Is a static method that uses local variables thread safe (eg in a web service)

In the following code assuming GetRandomValue() and DoSomethingElse() are thread safe, is the static method thread safe

public class Cach

public static int GetAValue(

int x = 0
x = GetRandomValue()
DoSomethingElse(x)
return x

The issue I think I need to understand is if there is only one instance of this method shared across all threads or one instance per thread. If there is only one instance shared across all threads then I assume there is only one instance of the local variable x and therefore this method is not thread safe

Comments pleas

Steve
Jul 21 '05 #1
2 6642
If there is only one instance shared across all threads then I assume there is only one instance of the local variable x and therefore this method is not thread safe?


There will be one x variable on the stack every time you enter the
method. Plus each thread has its own stack.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jul 21 '05 #2
This is thread safe: x is allocated on the stack and every thread has its
own stack.

The big deal is not really with static methods, but with static variables.
Static variables (and any object they may reference directly or indirectly)
may be accessed concurrently by several threads. So, you need to synchronize
access to static variables. But don't worry about local variables in static
methods.

Bruno.

"Steve" <an*******@discussions.microsoft.com> a écrit dans le message de
news:F5**********************************@microsof t.com...
Is a static method that uses local variables thread safe (eg in a web service)?
In the following code assuming GetRandomValue() and DoSomethingElse() are thread safe, is the static method thread safe?
public class Cache
{
public static int GetAValue()
{
int x = 0;
x = GetRandomValue();
DoSomethingElse(x);
return x;
}
}

The issue I think I need to understand is if there is only one instance of this method shared across all threads or one instance per thread. If there
is only one instance shared across all threads then I assume there is only
one instance of the local variable x and therefore this method is not thread
safe?
Comments please

Steve

Jul 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

22 posts views Thread by Steve - DND | last post: by
10 posts views Thread by Marek | last post: by
4 posts views Thread by Jimmy | last post: by
3 posts views Thread by Adam | last post: by
10 posts views Thread by Fred Mertz | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.