473,230 Members | 1,384 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,230 software developers and data experts.

Thread safety and member variables

Hi all,

I am wondering about thread safety and member variables. If I have
such a class:

class foo {
private float m_floater = 0.0;
public void bar(){
m_floater = true;
}
}

Is the variable m_floater thread safe? If I write a test program and
run it in VS2005, the m_floater variable ends up in the locals window
in my debugger (for each thread) so it would seem that it is thread
safe. I am assuming this would change if I made my member variable
into somthing that was stored on the managed heap? (i.e. each thread
has its own stack but there is only one heap available for storage).

thanks for helping with this seemingly simple question.
HC
Aug 13 '08 #1
13 11365
Edit:
m_floater = true should be m_floater = 17.7
Aug 13 '08 #2
On Wed, 13 Aug 2008 16:49:41 -0700, <He*************@googlemail.comwrote:
I am wondering about thread safety and member variables. If I have
such a class:

class foo {
private float m_floater = 0.0;
public void bar(){
m_floater = true;
}
}

Is the variable m_floater thread safe?
No, not at all. What about that code makes you think it would be?
If I write a test program and
run it in VS2005, the m_floater variable ends up in the locals window
in my debugger (for each thread) so it would seem that it is thread
safe.
Firstly, you're not going to see a member field show up in the "Locals"
window, except as a descendant of the implicit "this" variable. It's not
a local variable, but the "this" variable is. Second, if all it took to
make a member field "thread safe" was for it to be, well...a member field,
then all classes would be thread safe by default. That's definitely not
true.
I am assuming this would change if I made my member variable
into somthing that was stored on the managed heap? (i.e. each thread
has its own stack but there is only one heap available for storage).
Your class "foo" is a reference type, and so is always allocated from the
heap. So any instance fields are also stored on the heap, where the class
is (they are, after all, part of the class). You can't make your "member
variable into something that was stored on the managed heap". It already
is.

It's true that local variables are inherently thread safe, being
accessible only from the thread in which the method where they are
declared is executing. But that has nothing to do with things inside
classes, since you can't store a class in a local variable. You can only
store a _reference_ to a class in a local variable, and that reference
will always refer to data stored in the heap. Thus, without some sort of
synchronization, any instance member of the class is not thread safe (any
static member isn't either, but that's a separate question :) ).

Finally, lest you start thinking that this is a class-only thing, and that
value types (i.e. structs) then must be thread-safe, that would only be
true for structs that are only ever declared as local variables inside
methods. A struct used as the type for a member of a class would still
wind up being allocated on the heap with the rest of the class, and so
would not inherit the thread safety a struct declared as a local variable
would.

Pete
Aug 14 '08 #3
Peter Duniho wrote:
On Wed, 13 Aug 2008 16:49:41 -0700, <He*************@googlemail.comwrote:
>I am wondering about thread safety and member variables. If I have
such a class:

class foo {
private float m_floater = 0.0;
public void bar(){
m_floater = true;
}
}

Is the variable m_floater thread safe?

No, not at all. What about that code makes you think it would be?
Data are never thread safe in themselves. Data combined with
how they are used can be thread safe or not.

Actually the above code is thread safe.

It is also useless, so the benefits are not that big.

Arne
Aug 14 '08 #4
On Aug 13, 8:18 pm, Arne Vajhj <a...@vajhoej.dkwrote:
Peter Duniho wrote:
On Wed, 13 Aug 2008 16:49:41 -0700, <Henri.Chinas...@googlemail.comwrote:
I am wondering about thread safety and member variables. If I have
such a class:
class foo {
private float m_floater = 0.0;
public void bar(){
m_floater = true;
}
}
Is the variable m_floater thread safe?
No, not at all. What about that code makes you think it would be?

Data are never thread safe in themselves. Data combined with
how they are used can be thread safe or not.

Actually the above code is thread safe.

It is also useless, so the benefits are not that big.

Arne
I read Peter's response, makes great sense, thanks. So why then, do
you state that the above code is thread safe? Have I missed something
else?

thanks,
HC
Aug 14 '08 #5
On Wed, 13 Aug 2008 22:24:33 -0700, <He*************@googlemail.comwrote:
[...]
>Actually the above code is thread safe.

It is also useless, so the benefits are not that big.

Arne

I read Peter's response, makes great sense, thanks. So why then, do
you state that the above code is thread safe? Have I missed something
else?
Arne can be enigmatic sometimes. I suspect he does that intentionally.

Look at your class carefully. If we assume that that's _all_ of your
class, then there's nothing in it that could possibly be affected by
threading. No code in the class ever examines the "m_floater" variable
and it's private which means no code outside the class ever examines it
either. So it doesn't really matter if and when it gets assigned some new
value.

Personally, I figured that for the sake of discussion it made sense to
assume that there's more to your class than just what you posted.
Degenerate cases are mostly useful as base cases for induction, not
general conversation. :)

But clearly Arne felt otherwise, and took your code sample literally. And
yes, taken exactly as-is, there's no hazard using the class you posted in
a multi-threaded environment. In that sense, it's completely
thread-safe. :)

Pete
Aug 14 '08 #6
On Aug 14, 10:29*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Wed, 13 Aug 2008 22:24:33 -0700, <Henri.Chinas...@googlemail.comwrote:
[...]
Actually the above code is thread safe.
It is also useless, so the benefits are not that big.
Arne
I read Peter's response, makes great sense, thanks. So why then, do
you state that the above code is thread safe? Have I missed something
else?

Arne can be enigmatic sometimes. *I suspect he does that intentionally.

Look at your class carefully. *If we assume that that's _all_ of your *
class, then there's nothing in it that could possibly be affected by *
threading. *No code in the class ever examines the "m_floater" variable*
and it's private which means no code outside the class ever examines it *
either. *So it doesn't really matter if and when it gets assigned some new *
value.
It's more than that. A single variable of certain types, including
bool (but in general, any primitive type with sizeof <= 4, IntPtr,
pointers, and object references), is always thread-safe with respect
to reads and writes which only touch that variable. It's because the
C# spec guarantees that all such reads and writes are atomic (on the
other hand, writing a long or a double variable may not be atomic, and
needs to be guarded in case of concurrent access).
Aug 14 '08 #7
On Wed, 13 Aug 2008 23:40:57 -0700, Pavel Minaev <in****@gmail.comwrote:
>[...]
No code in the class ever examines the "m_floater" variable and it's
private which means no code outside the class ever examines it either.
*So it doesn't really matter if and when it gets assigned some new *
value.

It's more than that.
No, it really is just that.
A single variable of certain types, including
bool (but in general, any primitive type with sizeof <= 4, IntPtr,
pointers, and object references), is always thread-safe with respect
to reads and writes which only touch that variable.
Not true. First, if the variable isn't marked "volatile" (and it's not in
the example code we're talking about) it's still not thread-safe because
the compiler is allowed to generate code that could cache the value
somewhere invisible to some other thread.

In the code in question, the thread-safety comes only because it never
reads the variable. (By the way, because it always writes a constant,
even if the type wasn't 32 bits wide it'd still be safe, because all
writes would be doing the same thing).

More importantly, whether such a variable is thread-safe depends on how
it's used. Assuming the variable is properly marked as "volatile" and is
only ever assigned then yes, that would be thread-safe. But contrary to
your statement, being a type of 32 bits wide isn't in and of itself
sufficient for being thread-safe. For example:

class Test
{
volatile int i = 0;

void Method()
{
i = i + 1;
}
}

That's not thread-safe, even though the variable "i" is a 32 bit type.
There's more to thread-safety than just what the CPU can do with a
specific memory location.

Pete
Aug 14 '08 #8
On Aug 14, 10:52*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
A single variable of certain types, including
bool (but in general, any primitive type with sizeof <= 4, IntPtr,
pointers, and object references), is always thread-safe with respect
to reads and writes which only touch that variable.

Not true. *First, if the variable isn't marked "volatile" (and it's notin *
the example code we're talking about) it's still not thread-safe because *
the compiler is allowed to generate code that could cache the value *
somewhere invisible to some other thread.
Yes; I should have probably clarified that what I said was true only
with respect to a single read/write, not a sequence of those, even if
they all involve the same variable.

Of course, it is a moot point, since saying that "a variable is thread-
safe" - which is what I did - is a rather meaningless thing in and of
itself, since it's the code that can be thread-safe or not, not values
or storage locations by themselves. For values, the applicable term is
"atomic", which is what I should have used instead.

Aug 14 '08 #9
On Thu, 14 Aug 2008 00:44:10 -0700, Pavel Minaev <in****@gmail.comwrote:
[...]
Of course, it is a moot point, since saying that "a variable is thread-
safe" - which is what I did - is a rather meaningless thing in and of
itself, since it's the code that can be thread-safe or not, not values
or storage locations by themselves. For values, the applicable term is
"atomic", which is what I should have used instead.
I agree. :) That's not exactly the same as "thread safe", though it's
related.

That said, you still need "volatile" if you expect to take advantage of
the atomicity as a part of thread-safety. Otherwise, you have nice atomic
reads and writes, but not necessarily to the same location each thread is
using.

Pete
Aug 14 '08 #10
He*************@googlemail.com wrote:
On Aug 13, 8:18 pm, Arne Vajhj <a...@vajhoej.dkwrote:
>Peter Duniho wrote:
>>On Wed, 13 Aug 2008 16:49:41 -0700, <Henri.Chinas...@googlemail.comwrote:
I am wondering about thread safety and member variables. If I have
such a class:
class foo {
private float m_floater = 0.0;
public void bar(){
m_floater = true;
}
}
Is the variable m_floater thread safe?
No, not at all. What about that code makes you think it would be?
Data are never thread safe in themselves. Data combined with
how they are used can be thread safe or not.

Actually the above code is thread safe.

It is also useless, so the benefits are not that big.

I read Peter's response, makes great sense, thanks. So why then, do
you state that the above code is thread safe? Have I missed something
else?
The code you posted is thread safe.

When you add all the real code, then it may be:
thread safe
not thread safe
If we introduce the volatile aspect it may be:
thread safe without volatile
not thread safe without volatile but thread safe with volatile
not thread safe with volatile

It depends on your code.

Arne
Aug 15 '08 #11
Peter Duniho wrote:
On Wed, 13 Aug 2008 22:24:33 -0700, <He*************@googlemail.comwrote:
>[...]
>>Actually the above code is thread safe.

It is also useless, so the benefits are not that big.

I read Peter's response, makes great sense, thanks. So why then, do
you state that the above code is thread safe? Have I missed something
else?

Arne can be enigmatic sometimes. I suspect he does that intentionally.

Look at your class carefully. If we assume that that's _all_ of your
class, then there's nothing in it that could possibly be affected by
threading. No code in the class ever examines the "m_floater" variable
and it's private which means no code outside the class ever examines it
either. So it doesn't really matter if and when it gets assigned some
new value.

Personally, I figured that for the sake of discussion it made sense to
assume that there's more to your class than just what you posted.
Degenerate cases are mostly useful as base cases for induction, not
general conversation. :)

But clearly Arne felt otherwise, and took your code sample literally.
And yes, taken exactly as-is, there's no hazard using the class you
posted in a multi-threaded environment. In that sense, it's completely
thread-safe. :)
Since it is impossible to guess whether the code not posted is thread
safe or not, then ...

Arne
Aug 15 '08 #12
Peter Duniho wrote:
Not true. First, if the variable isn't marked "volatile" (and it's not
in the example code we're talking about) it's still not thread-safe
because the compiler is allowed to generate code that could cache the
value somewhere invisible to some other thread.
You can not conclude that.

There are other ways of ensuring visibility between threads than
volatile.

Arne

Aug 15 '08 #13
On Thu, 14 Aug 2008 19:16:58 -0700, Arne Vajhøj <ar**@vajhoej.dkwrote:
Peter Duniho wrote:
>Not true. First, if the variable isn't marked "volatile" (and it's not
in the example code we're talking about) it's still not thread-safe
because the compiler is allowed to generate code that could cache the
value somewhere invisible to some other thread.

You can not conclude that.

There are other ways of ensuring visibility between threads than
volatile.
That's true. But none of those other memory barriers exist in the code
that was posted. The "volatile" keyword would be the simplest way to
address that.
Aug 15 '08 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause...
11
by: dee | last post by:
OleDbCommand class like many .NET classes has the following description in its help file: "Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for...
4
by: | last post by:
I find in the documentation the following Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not...
6
by: Dennis | last post by:
I have a question about thread safety in a VB application written using Visual Studio.Net 2003. Here is the situation... I am running a process thread in a modal dialog. I have written it so...
7
by: Chad Zalkin | last post by:
We are evaluating some old code that was written as part of our math library. This code uses some optimizations that I'm not sure are necessary or safe, but is a source of debate between my...
4
by: Warren Sirota | last post by:
Hi, I've got a method that I want to execute in a multithreaded environment (it's a specialized spider. I want to run a whole bunch of copies at low priority as a service). It works well running...
15
by: Laser Lu | last post by:
I was often noted by Thread Safety declarations when I was reading .NET Framework Class Library documents in MSDN. The declaration is usually described as 'Any public static (Shared in Visual...
9
by: cgwalters | last post by:
Hi, I've recently been working on an application which does quite a bit of searching through large data structures and string matching, and I was thinking that it would help to put some of this...
6
by: Olumide | last post by:
Hi - I've got a class that contains static member functions alone, all of whose arguments are passed by reference as shown below: class MySpiffyClass{ // no constructor, destructor or...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.