473,795 Members | 3,024 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 ISimpleWorkerTh read
{
private volatile bool abortRequested;

public ISimpleWorkerTh read()
{
abortRequested = false;
}

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

public abstract void DoStuff() // Polls AbortRequested

protected bool AbortRequested
{
get {return abortRequested; }
}

public void Abort()
{
abortRequested = true;
}
}
Nov 16 '05 #1
3 2688
Invalid <in*****@invali d.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.co m>
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.co m> wrote in message news:MP******** *************** *@msnews.micros oft.com...
Invalid <in*****@invali d.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*****@invali d.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.co m>
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
13372
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? Kind regards, Sune Alexandersen
1
3603
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 with intent to update, the first one grab the record will create a row lock on the current row reading, before it update, other user can't access the same record with intent for update read, but can access with read only type. so when the first...
3
233
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 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....
5
4668
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 RichEditBox. To give you some idea of the approach I took... private static RichTextBox rtb; private delegate void RtbAppendTextHandler(string output); private static RtbAppendTextHandler RtbAppendText; Log.Init(RichTextBox richTextBox,...
14
3839
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 + 64)) Next Lock(1, 5, 10)
4
2160
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 for execution using ThreadStart Delegate say "worker" method . Now in the worker method there's a piece of code :
4
2264
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 machine, update it and then upload it back to ftp, and at the same time if some one else downloads the same file for the modification, then the data will be overwritten. so is there a way in Python script where i can lock the file, so that no one...
94
30357
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
2821
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 ensure Same thread Can’t be stated again. In our Application each thread is mapped to row .So lock is acquired on a row.
0
9672
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
9519
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
10439
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
10215
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...
1
7541
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
5437
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...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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.