473,763 Members | 7,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 11472
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.co mwrote:
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.co mwrote:
>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 Vajhøj <a...@vajhoej.d kwrote:
Peter Duniho wrote:
On Wed, 13 Aug 2008 16:49:41 -0700, <Henri.Chinas.. .@googlemail.co mwrote:
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.co mwrote:
[...]
>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...@nn owslpianmk.com>
wrote:
On Wed, 13 Aug 2008 22:24:33 -0700, <Henri.Chinas.. .@googlemail.co mwrote:
[...]
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.c omwrote:
>[...]
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...@nn owslpianmk.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.c omwrote:
[...]
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

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

Similar topics

4
6652
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 potential problems for thread-safety. So far, I'm only confused. I need a proper explanation for the concept so I can understand how to write thread-safe functions in the future. My apologies for posting a long routine.
11
2255
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 multithreaded operations. Any instance members are not guaranteed to be thread safe." I have 2 questions: 1. I thought dynamic variables are thread-safe since threads have their own
4
1310
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 guaranteed to be thread safe. Then, I go to the members documentation and I find public methods or
6
1137
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 the user cannot exit the dialog until the thread completes (unless they click a button to explicitly interrupt and destroy the thread). My question...
7
2308
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 coworkers. Method 1 includes a temporary storage varriable at class scope. Method 2 includes a temporary storage varriable at method scope. Method 3 includes a temporary static storage varriable at method scope. Are any of the methods better than...
4
2572
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 as a single application. I was wondering if there is a "Thread-Safety Analysis Wizard"? I'm sure I'm grossly off-base with the following, so I'm prepared to be embarrassed. Please point me in the right direction!
15
2784
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 Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.' So, does this mean All the static/shared methods written in .NET compatible programming language, such as C#, VB.NET, are guaranteed to be...
9
1864
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 CPU-intensive work in another thread, but of course this won't work because of Python's GIL. There's a lot of past discussion on this, and I want to bring it up again because with the work on Python 3000, I think it is worth trying
6
3884
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 variables, just static members static void FirstFunction( args & ); static void SecondFunction( args & ); static void ThirdFunction( args & );
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10144
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9937
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.