static member method

G

Guest

Hi,

I have the following class:
class MyClass
{

public static void SomeMethod(string str)
{
string local = "AAA";
string test = local + str;
.....
}

}

This public static method can be used by multiple threads. Is it needed to
lock the local variable test, or every thread will have its own copy of this
variable as it is local?

Thanks,
Lubomir
 
B

Bruce Wood

Hi,

I have the following class:
class MyClass
{

public static void SomeMethod(string str)
{
string local = "AAA";
string test = local + str;
.....
}

}

This public static method can be used by multiple threads. Is it needed to
lock the local variable test, or every thread will have its own copy of this
variable as it is local?

Every thread will have its own copy on the stack.

Data is shared across threads only if the data item itself is marked
"static".
 
B

Bruce Wood

Every thread will have its own copy on the stack.

Data is shared across threads only if the data item itself is marked
"static".

Sorry. That was inaccurate. Teach me to type fast and think later.

Data will be shared across threads only if the item is declared as a
field in the object, regardless of whether it's a static or instance
member.

Local variables within methods are stored on the stack and so there is
one per thread.

So... you're still OK. It's just that my explanation of _why_ your
code is OK was wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top