473,467 Members | 1,964 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Reading Integers from Threads

I have a class with a private Int32 data member that gets modified from
multiple background threads. To synchronize these modifications I use the
lock statement:

Int32 count = 0;
object countLock = new object();

....
lock (countLock) count++;

....
lock(countLock) count = newValue;
My question is that when I wish to read this value (from yet another thread)
do I need to wrap it in a lock statement. For example, the class has the
following property:

public Int32 Count{get{return count;}}

The reading of the value is done extensively and I do not wish to have the
overhead of the lock statement. Can a thread lose it's turn in the middle of
a lock statement? If so, is it possible that the Int32 field is only
partially updated with it's new value and when I go to read it? What if my
field was an Int64?

Thanks,

- Fred
Nov 17 '05 #1
4 1661
When working with Int32, instead of using locks, you can use the
Increment, Decrement and Exchange methods on the Interlocked class. On
a 32bit system, they are guarantteed to be atomic, not only with each
other, but with other operations as well. you don't need a lock to
read.

same is not true for Int64 on a 32bit system, however. Reading without
a lock could result in partially updated data.

Fred West wrote:
I have a class with a private Int32 data member that gets modified from
multiple background threads. To synchronize these modifications I use the
lock statement:

Int32 count = 0;
object countLock = new object();

...
lock (countLock) count++;

...
lock(countLock) count = newValue;
My question is that when I wish to read this value (from yet another thread)
do I need to wrap it in a lock statement. For example, the class has the
following property:

public Int32 Count{get{return count;}}

The reading of the value is done extensively and I do not wish to have the
overhead of the lock statement. Can a thread lose it's turn in the middle of
a lock statement? If so, is it possible that the Int32 field is only
partially updated with it's new value and when I go to read it? What if my
field was an Int64?

Thanks,

- Fred


Nov 17 '05 #2
In addition to what Daniel said, you can easily encapsulate this in a
method and property in the class like this:

public int Count
{
get
{
// Lock.
lock (countLock)
{
// Return the value.
return countLock;
}
}
}

public int IncrementCount()
{
// Call the overload, passing 1.
return IncrementCount(1);
}

public int IncrementCount(int amount)
{
// Lock.
lock (countLock)
{
// Increment the count.
count += amount;

// Return the new value.
return count;
}
}

Then, you can use these methods everywhere, and not have to worry about
handling the lock in each situation. Ahh, the joys of code encapsulation.
=)

Also, if you were doing just assignment or a read, you could declare the
variable as volatile, but that would limit the "thread-safeness" of your
operation to just that assignment or read (and it doesn't work on 64-bit
values).

And no, a thread can not lose it's value in the middle of a lock
statement. If you try and access a variable where all access is blocked by
lock statements, those statements will wait until they can acquire the lock
in that thread.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Daniel Jin" <sh********@yahoo.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.com...
When working with Int32, instead of using locks, you can use the
Increment, Decrement and Exchange methods on the Interlocked class. On
a 32bit system, they are guarantteed to be atomic, not only with each
other, but with other operations as well. you don't need a lock to
read.

same is not true for Int64 on a 32bit system, however. Reading without
a lock could result in partially updated data.

Fred West wrote:
I have a class with a private Int32 data member that gets modified from
multiple background threads. To synchronize these modifications I use the
lock statement:

Int32 count = 0;
object countLock = new object();

...
lock (countLock) count++;

...
lock(countLock) count = newValue;
My question is that when I wish to read this value (from yet another
thread)
do I need to wrap it in a lock statement. For example, the class has the
following property:

public Int32 Count{get{return count;}}

The reading of the value is done extensively and I do not wish to have
the
overhead of the lock statement. Can a thread lose it's turn in the middle
of
a lock statement? If so, is it possible that the Int32 field is only
partially updated with it's new value and when I go to read it? What if
my
field was an Int64?

Thanks,

- Fred

Nov 17 '05 #3

"Fred West" <fr*************@yahoo.com> wrote in message
news:Og****************@TK2MSFTNGP09.phx.gbl...
I have a class with a private Int32 data member that gets modified from
multiple background threads. To synchronize these modifications I use the
lock statement:

Int32 count = 0;
object countLock = new object();

...
lock (countLock) count++;

...
lock(countLock) count = newValue;
My question is that when I wish to read this value (from yet another
thread) do I need to wrap it in a lock statement. For example, the class
has the following property:

public Int32 Count{get{return count;}}

The reading of the value is done extensively and I do not wish to have the
overhead of the lock statement. Can a thread lose it's turn in the middle
of a lock statement? If so, is it possible that the Int32 field is only
partially updated with it's new value and when I go to read it? What if my
field was an Int64?

Thanks,

- Fred


Int32 reads are atomic operations, so the value you get cannot be partially
updated, however without synchronizing the access, you aren't guaranteed to
read the last value written on multi CPU boxes.
If all you need to protect is a simple integer value, you might consider to
use Interlocked methods instead of using such fine grained locks to perform
atomic, thread-safe operations on Int32 values, they are faster than taking
locks and have less overhead when contention rate is high. However, you
should not use them on longer values (Int64, Doubles), for such values I
would suggest you to use locks which are extremely fast in non-contention
cases.

Willy.
Nov 17 '05 #4

Daniel Jin wrote:
you don't need a lock to read.


You still need some synchronization mechanism to read the value to
guarentee that you seeing the changes other threads are making. Read
the following article on volatility for more information.

<http://www.yoda.arachsys.com/csharp/threads/volatility.shtml>

Brian

Nov 17 '05 #5

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

Similar topics

6
by: bas | last post by:
hey, I am having a lot of trouble trying to get this program to work properly. It is supposed to read integers from a file and place them into the categories for inventory. The problem seems to...
10
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the...
9
by: Eric Lilja | last post by:
Hi! I have a program with a class that needs to be able to write itself to a file in clear text format. The file has two integers and vector of struct objects. The struct has a string that can...
16
by: WATYF | last post by:
Hi there... I have a huge text file that needs to be processed. At the moment, I'm loading it into memory in small chunks (x amount of lines) and processing it that way. I'd like the process to be...
4
by: Shark | last post by:
Hi, I need a help. My application reads data from COM port, this data is then parsed and displyed on: 1. two plotters 2. text box. I'm using Invoke method to update UI when new data is...
3
by: Pinux | last post by:
Hi, I am writing a multi-threads encryption application. The idea of the code is to create a number of threads to encrypt files. I have a thread pool say the maximum threads is 10. If the number...
9
by: Hal Vaughan | last post by:
I've done a fair amount of Googling for information on reading the serial port in C++ (and in Linux). Unfortunately, out of every 4 hits, 1 seems to be an unanswered question, 1 is someone saying,...
4
by: C++ Newbie | last post by:
Suppose I have a text file with the input: 1 2 3 4 5 6 7 8 9 10 ! Comment: Integers 1 - 10 How do I write a C++ program that reads in this line into a 10-element vector and ignores the...
19
by: Hapa | last post by:
Does only reading (never writing) of a variable need thread synchronisation? Thanks for help? PS. Anybody knows a Visual C++ news group?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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,...
1
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...
0
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...
0
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 ...

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.