473,668 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

volatile member variable with Interlocked

I have an member variable (int) that is accessed by multiple threads using
Interlocked.Inc rement(), Interlocked.Dec rement(), and read directly.

Using volatile gives me "CS0420: a reference to a volatile field will not be
treated as volatile" warnings when using the Interlocked functions, which I
can easily disable with "#pragma warning disable 420".

Should this variable be marked volatile? Is volatile necessary in this
case?

Thanks!
Mark

--
Mark Salsbery
Microsoft MVP - Visual C++
Oct 25 '08 #1
5 3888
Mark Salsbery [MVP] wrote:
I have an member variable (int) that is accessed by multiple threads
using Interlocked.Inc rement(), Interlocked.Dec rement(), and read directly.

Using volatile gives me "CS0420: a reference to a volatile field will
not be treated as volatile" warnings when using the Interlocked
functions, which I can easily disable with "#pragma warning disable 420".
Annoying, isn't it? They should have built in an exception for the
Interlocked functions.

One way to avoid it without disabling it is to remove the volatile qualifier
and explicitly use Thread.Volatile Read() instead. This might be less
intuitive and easier to get wrong than relying on volatile, though. Then
again, just using interlocked fields is less intuitive than using monitors. :-)
Should this variable be marked volatile? Is volatile necessary in this
case?
In all likelihood, yes. You've got atomic reads and writes covered, but if
you don't use volatile, the compiler is free to "optimize" access in the
threads that read the value. This means there could be an arbitrary delay
between the interlocked updates and the reader(s) seeing them (technically
it's even legal if things are optimized in such a way that the readers
*never* see the updates, but I've never seen the compiler produce code like
that).

--
J.
Oct 26 '08 #2
"Jeroen Mostert" <jm******@xs4al l.nlwrote in message
news:49******** *************@n ews.xs4all.nl.. .
One way to avoid it without disabling it is to remove the volatile
qualifier and explicitly use Thread.Volatile Read() instead.

Thread.Volatile Read() ! That's what I was looking for - I hadn't seen that
before.

Sure, I could use lock/Monitor but it's a relatively heavyweight solution
for incrementing/decrementing an integer atomically.

I realize this has been discussed many times here before - I guess I used
the wrong search keywords last time.

From everything I can find, it seems Interlocked accesses the variable with
volatile semantics - I was just missing a way to read the variable the same
way.

Thank you Jeroen!

Cheers,
Mark

--
Mark Salsbery
Microsoft MVP - Visual C++

Oct 27 '08 #3
Mark Salsbery [MVP] wrote:
Sure, I could use lock/Monitor but it's a relatively heavyweight
solution for incrementing/decrementing an integer atomically.
Look at it the other way around: *not* using monitors is an optimization,
and like all optimizations probably not something you should use from the
get-go until you can show that you need it.

Multithreading is hard enough, once you abandon monitors and use primitives
directly it *really* gets hard. Before you know it you're getting a headache
reading twelve-page threads on memory models and wondering whether this read
over here really is safe on an Itanium.

That's my experience, at least -- my respect goes out to all the people who
have no trouble applying these things in their daily job. I'm holding out
for better library support. :-)

--
J.
Oct 27 '08 #4
On Oct 27, 6:23*pm, Jeroen Mostert <jmost...@xs4al l.nlwrote:
Mark Salsbery [MVP] wrote:
Sure, I could use lock/Monitor but it's a relatively heavyweight
solution for incrementing/decrementing an integer atomically.

Look at it the other way around: *not* using monitors is an optimization,
and like all optimizations probably not something you should use from the
get-go until you can show that you need it.

Multithreading is hard enough, once you abandon monitors and use primitives
directly it *really* gets hard. Before you know it you're getting a headache
reading twelve-page threads on memory models and wondering whether this read
over here really is safe on an Itanium.

That's my experience, at least -- my respect goes out to all the people who
have no trouble applying these things in their daily job. I'm holding out
for better library support. :-)
That's pretty much exactly what I'd say, too.

Another way of doing an atomic read is with
int y = Interlocked.Com pareExchange(re f x, 0, 0)
which will basically read and conditionally exchange with the same
value.

Jon
Oct 28 '08 #5

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:d3******** *************** ***********@u28 g2000hsc.google groups.com...
On Oct 27, 6:23 pm, Jeroen Mostert <jmost...@xs4al l.nlwrote:
Another way of doing an atomic read is with
int y = Interlocked.Com pareExchange(re f x, 0, 0)
which will basically read and conditionally exchange with the same
value.

Thanks Jon.

Mark

--
Mark Salsbery
Microsoft MVP - Visual C++

>
Jon
Oct 29 '08 #6

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

Similar topics

15
10594
by: DanGo | last post by:
Hi All, I'm trying to get my head around synchronization. Documentation seems to say that creating a volatile field gives a memorybarrier. Great! But when I do a little performance testing Thread.MemoryBarrier is 40 times slower than accessing a volatile int. Also I don't see any significant difference between the time to increment a volatile int and a
22
2287
by: Assaf | last post by:
hi all i know that i should not cross-post, but i am not sure to which group to post this question. 2 quesions about volatile: 1. i use volatile when 2 threads access the same variable is this the proper use of volatile?
14
7438
by: Pierre | last post by:
Using the "volatile" keyword, creates a problem if I intend to use any of the interlocked APIs. The compiler generates an error if I use the following line, for example: Interlocked.Increment(ref count); The error says that a volatile field cannot be used as ref or out, but if I don't use the volatile field, the value may be cached away in some method that is just reading the field.
10
2892
by: Lau Lei Cheong | last post by:
Hello, I really need to use volatile System.Int64 for a .NET v1.1 program in C#. But the compiler complains "a volatile field can not be of type long". How to work around it? Or is there any other way to get similar effect for Int64 type? Another question less urging question is, why long variables can't be used as volatile? I understand that in 32-bit arch. 64-bit operations are not atomic, but seems that there could be locks or so...
3
1779
by: Amir Shitrit | last post by:
Hello. How come it's safe to read non-volatile fields that are shared across threads using locks for synchronization (for example, Monitor.Enter or EventWaitHandle), but it's not safe to access them if no lock synchronization mechanisms are employed? Whe using locks, I'm I guaranteed that when accessing shared non-volatile fields I will get the most up-to-date values? Thanks.
94
30276
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
0
8462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8381
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
8893
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...
0
8799
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7401
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
6209
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
5681
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4205
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...
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.