473,320 Members | 1,707 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,320 software developers and data experts.

Safely modifying variables in a multithreaded environment.

Hello,

I want to use a variable as a signal to the thread that it should stop
what it's doing (code below). As a rule, should I lock an object only
when I am writing to it or do I have to lock on reading as well? For
instance, consider the following code:

//running in a non-GUI thread
foreach (object o in objects)
{
...
if (SignalObject.StopSignalDetected) break;
}
//running in the GUI thread.
void btnStop_Click(...)
{
lock (SignalObject)
{
SignalObject.StopSignalDetected = true;
}
}

Is SignalObject.StopSignalDetected safe here? Or should I lock it in
the non-GUI thread as well, even though it will only read it?

Thanks
Nov 17 '05 #1
4 1285
Frank Rizzo <no**@none.com> wrote:
I want to use a variable as a signal to the thread that it should stop
what it's doing (code below). As a rule, should I lock an object only
when I am writing to it or do I have to lock on reading as well?


In general, you need to lock for reading as well, for two reasons:

1) To pick up changes in writing threads atomically
2) To guarantee that pick up changes in writing threads at all

See http://www.pobox.com/~skeet/csharp/t...latility.shtml

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Usually when you have a number of operations to carry out as one logical unit
that require reading and writing then you should lock the variable, for
example:

Company A requests person A's bank balance (it's $100)
Company B requests person A's bank balance (it's $100)
Company A adds $100 -> total is $200 (because it read $100)
Company B debits $25 -> total is $75 (because it read $100)
Company A saves the value $200 to user A's account
Company B saves the value $75 to user A's account

At the end of the day person A only has $75 in his account instead of $175.

We had one logical unit of work but it took many steps, so for the bank
account which here is a resource that is being competed for we need to lock
so only one thread can access the rsource at any time.

In your case I am guessing SignalObject.StopSignalDetected is just assigning
to a variable or returning a boolean internally, so there are not a number of
steps so you really don't need to lock this variable.

Hope that helps
Mark.

"Frank Rizzo" wrote:
Hello,

I want to use a variable as a signal to the thread that it should stop
what it's doing (code below). As a rule, should I lock an object only
when I am writing to it or do I have to lock on reading as well? For
instance, consider the following code:

//running in a non-GUI thread
foreach (object o in objects)
{
...
if (SignalObject.StopSignalDetected) break;
}
//running in the GUI thread.
void btnStop_Click(...)
{
lock (SignalObject)
{
SignalObject.StopSignalDetected = true;
}
}

Is SignalObject.StopSignalDetected safe here? Or should I lock it in
the non-GUI thread as well, even though it will only read it?

Thanks

Nov 17 '05 #3
Jon Skeet [C# MVP] wrote:
Frank Rizzo <no**@none.com> wrote:
I want to use a variable as a signal to the thread that it should stop
what it's doing (code below). As a rule, should I lock an object only
when I am writing to it or do I have to lock on reading as well?

In general, you need to lock for reading as well, for two reasons:

1) To pick up changes in writing threads atomically


Jon, great link. I learned a lot. And your article is correct: there is
quite a bit of a performance hit in my app if I lock on reading and
writing. One quick question though. If I just lock on writing and
don't care whether the reading thread reads it the first time (second or
third time is fine), am I ok?
2) To guarantee that pick up changes in writing threads at all

See http://www.pobox.com/~skeet/csharp/t...latility.shtml

Nov 17 '05 #4
Frank Rizzo <no**@none.com> wrote:
In general, you need to lock for reading as well, for two reasons:

1) To pick up changes in writing threads atomically
Jon, great link. I learned a lot. And your article is correct: there is
quite a bit of a performance hit in my app if I lock on reading and
writing.


Is there? Is it truly significant? I believe in *most* real-world cases
the hit isn't worth worrying about. A test case which does nothing but
read and write with multiple threads might have problems, but a real
app which is doing other things won't have problems - usually! It
depends on what the app is doing, of course.
One quick question though. If I just lock on writing and
don't care whether the reading thread reads it the first time (second or
third time is fine), am I ok?


Well, it's not just a case of "second or third time" - it's whether the
reading thread *ever* sees the change. That isn't guaranteed, although
to be honest if you call other methods (which aren't inlined) I believe
there's a memory barrier at that point.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5

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

Similar topics

3
by: Anthony | last post by:
Hi, How does (Can?) the stream mechanism work in multithreaded programs? I want to implement cout in my multithreaded program.
9
by: Simon Harvey | last post by:
Hi all, In my project I have made a number of helper methods static. As I understand it, this will create the problem that multiple threads could access the static method at the same time and...
1
by: nin234 | last post by:
I tried searching the newgroups for an answer to this question. I found many related topics, but didn't find the exact answer I am looking for. I am implementing a class to aid in the logging...
9
by: nicolas.michel.lava | last post by:
Hi there, I have some trouble using STL containers. I'm working on a multithreaded (pthread) application making heavy usage of STL containers. All accesses to containers are made in locked...
0
by: shorti | last post by:
DB1 V8.2 DB2 Info Center has information on the subject that states in a multi function environment to include the EXEC SQL INCLUDE SQLCA statement in only one function and the remaining source...
2
by: requeth | last post by:
I have 12 possible error codes that can be placed in an attribute, and multiple attributes with this in an XML file. I am attempting to use an XSLT (which makes the data viewable to non technical...
4
by: vmpstr | last post by:
Hi, I am working on a multithreaded application, which also happens to use STL quite heavily. I'm running into the following problem (I'm sorry I can't post any code, because it is quite...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.