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

Is a lock required if...

I launch a worker thread that periodically reads a volatile bool
abortRequested, which could be set to true by my main form.
IOW, there is one thread that can read that bool and one different
thread that can set it. See code below for an overview.

In a C or C++ environment, my current approach would be
adequate (no need to acquire exclusive access to abortRequested).
I'm guessing that I'm still OK under C# because bool is a value
type. Correct?
public abstract class ISimpleWorkerThread
{
private volatile bool abortRequested;

public ISimpleWorkerThread()
{
abortRequested = false;
}

public void Start()
{
Thread t = new Thread(new ThreadStart(DoStuff));
t.Start();
}

public abstract void DoStuff() // Polls AbortRequested

protected bool AbortRequested
{
get {return abortRequested;}
}

public void Abort()
{
abortRequested = true;
}
}
Nov 16 '05 #1
3 2621
Invalid <in*****@invalid.invalid> wrote:
I launch a worker thread that periodically reads a volatile bool
abortRequested, which could be set to true by my main form.
IOW, there is one thread that can read that bool and one different
thread that can set it. See code below for an overview.

In a C or C++ environment, my current approach would be
adequate (no need to acquire exclusive access to abortRequested).
I'm guessing that I'm still OK under C# because bool is a value
type. Correct?


No - you're okay because the variable is volatile. If it weren't
volatile, you'd have to lock.

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

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message news:MP************************@msnews.microsoft.c om...
Invalid <in*****@invalid.invalid> wrote:
I launch a worker thread that periodically reads a volatile bool
abortRequested, which could be set to true by my main form.
IOW, there is one thread that can read that bool and one different
thread that can set it. See code below for an overview.

In a C or C++ environment, my current approach would be
adequate (no need to acquire exclusive access to abortRequested).
I'm guessing that I'm still OK under C# because bool is a value
type. Correct?
No - you're okay because the variable is volatile.


Thanks for the reply.

FWIW, I was thinking in terms of a simple read or write of a value type
being inherently atomic and thus thread-safe IF the variable is marked
volatile. I'm assuming that you could still get burned by a volatile object
if, say, one of its accessors needs to read or write multiple fields and
thus could be interrupted (?)
If it weren't volatile, you'd have to lock.


Well I have seen code that does a lock(this) and then manipulates
fields which aren't marked as volatile. I was actually surprised by
that, and I'm glad this has come up. Does locking on an object
cause it and only it to be treated in a volatile like manner, or are all
objects/values treated in a volatile like manner within a lock block?
Put another way, can you lock on one object and manipulate a
second object as long as the second object is only manipulated
when the first is locked? Example:

public class foo
{
SomeObject o1;
SomeOtherObject o2;

public void Test()
{
lock(o1)
{
if(o2.nonVolInt != 4)
o2.nonVolInt++;
}
}
}

In the above example, are we guaranteed that the memory
location associated with o2.nonVolInt is manipulated rather
than a register copy?
Nov 16 '05 #3
Invalid <in*****@invalid.invalid> wrote:
No - you're okay because the variable is volatile.
Thanks for the reply.

FWIW, I was thinking in terms of a simple read or write of a value type
being inherently atomic and thus thread-safe IF the variable is marked
volatile. I'm assuming that you could still get burned by a volatile object
if, say, one of its accessors needs to read or write multiple fields and
thus could be interrupted (?)


Yes indeed. Also you still have problems if you do something like:

volatileInt++;
If it weren't volatile, you'd have to lock.


Well I have seen code that does a lock(this) and then manipulates
fields which aren't marked as volatile.


I personally prefer not locking on "this", but that's a different
discussion (and one already going in another thread: "What's wrong with
lock(this)").
I was actually surprised by
that, and I'm glad this has come up. Does locking on an object
cause it and only it to be treated in a volatile like manner, or are all
objects/values treated in a volatile like manner within a lock block?
What happens is the when you enter a lock, it performs a volatile read.
That means that the compiler can't do anything to "move" a read which
is after the lock entry in the program code to before the lock entry.
It's a sort of memory barrier - sort of an "ignore any cached copies of
anything you've got" operation.

When you exit a lock, it effectively performs a volatile write, which
means that the compiler can't do anything to "move" a write which is
before the lock exit in the program code to after the lock exit. This
is a different type of memory barrier - a sort of "flush any write
operations you've got in your cache" operation.

Between them, and with the action of a lock preventing another thread
from entering the same lock, it means that so long as you lock on the
same reference before accessing/modifying a shared piece of memory,
you're okay. However, you can't lock on one reference in one place and
another reference in a different place - then you get the memory
barrier effects, but not the exclusion, so nastiness can still happen.
Put another way, can you lock on one object and manipulate a
second object as long as the second object is only manipulated
when the first is locked?
Spot on.
Example:

public class foo
{
SomeObject o1;
SomeOtherObject o2;

public void Test()
{
lock(o1)
{
if(o2.nonVolInt != 4)
o2.nonVolInt++;
}
}
}

In the above example, are we guaranteed that the memory
location associated with o2.nonVolInt is manipulated rather
than a register copy?


Absolutely - exception that o1 is null rather than a valid reference,
so you'd want:

SomeObject o1 = new SomeObject();

In fact, a register copy *could* be modified within the lock, but then
flushed during the exit of the monitor. However, you'll perform a
"real" read of the value of o2.nonVolInt first.

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

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

Similar topics

25
by: Sune A | last post by:
Hi All! I'm having problems with www.suneworld.com The thing is that I'd like to lock the width of the page, so that it won't adjust dynamically. Any CSS people out there that can help me? ...
1
by: xixi | last post by:
hi, we are using db2 udb v8.1 ESE with type 4 jcc driver. since DB2 can't support pessimistic locking , and our application required that, which means when both users try to access the same record...
3
by: Invalid | last post by:
I launch a worker thread that periodically reads a volatile bool abortRequested, which could be set to true by my main form. IOW, there is one thread that can read that bool and one different...
5
by: User N | last post by:
I have a log class with static methods that grab and release a mutex as required. The log class is designed to be called from both GUI and thread pool threads, and dump output to a logfile and a...
14
by: Gary Nelson | last post by:
Anyone have any idea why this code does not work? FileOpen(1, "c:\JUNK\MYTEST.TXT", OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.Shared) Dim X As Integer For X = 1 To 26 FilePut(1, Chr(X +...
4
by: Mrinal Kamboj | last post by:
Hi , I had a doubt regarding a piece of code with me , that has to do with System.Threading.Thread class . In it user instantiates an array of Thread class and to all of them assign a method...
4
by: muttu2244 | last post by:
hi all am trying to write some information into the file, which is located in ftp, and this file can be updated by number of people, but if at all i download a file from the ftp to my local...
94
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...
0
by: senthiltkp | last post by:
Hi, I'm new to DB2 and have little knowledge on database. i'm facing a Spin lock issue in db2.. Thread here am talking is Java thread..(Sepearte process) The spin Lock is acquired to...
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.