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

Question on Locking and Deadlocks

I'm trying to undertand some details on the C# "lock" statement. I came
across some code during a review and thought I spotted a deadlock scenario,
but the programmer said he'd taken it from a reliable source.

Does the following code contain a potential deadlock? or are the locks
granted to syncRoot specific to each method?
================================================== ========
private static readonly object syncRoot = new object();
private static object resource;

public static object Resource
{
get
{
if( resource == null )
{
lock( syncRoot )
{
resource = new object();
}
}
return resource;
}
}

public static void DoSomethingToResource()
{
lock( syncRoot )
{
object resourcePlaceHolder = Resource;
}
}
================================================== ========

TIA//
Mar 9 '07 #1
7 1508

"Chris Newby" <ch*********@rockcreekglobal.comwrote in message
news:uu**************@TK2MSFTNGP04.phx.gbl...
I'm trying to undertand some details on the C# "lock" statement. I came
across some code during a review and thought I spotted a deadlock
scenario, but the programmer said he'd taken it from a reliable source.
Not very reliable for real :)

the Reourse property is not thread safe, the comparison should be inside the
lock statement. If not it's possible to create two instances if two thread
happen to evaluate the if before it's assigned in either thread. NOTE that
I see the DoSomethingToResource and its locking, but as the Resource
property is public you can call it from another method that do not use the
lock.

The correct wa is

lock( syncRoot )
{
if( resource == null )

{
resource = new object();
}
}

Mar 9 '07 #2
Thanks Ignacio ... actually I made a mistake in the declaration. The private
field "resource" should have been declared volatile:

private static volatile object resource;

this would ensure that if one thread begins writing to "resource" any other
thread is blocked from reading it until the write operation is complete ...
correct?

also, the example I gave for DoSomethingToResource is not very good ...
let's suppose that it does something that requires a lock. Can I safely lock
on "syncRoot" from within DoSomethingToResource even though it references
the public property accessor "Resource"? or must I use a different reference
for creating the lock?

(note that normally, i would in fact use a different object reference to be
on the safe side. but i'm still curious)

Thanks!

"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
message news:OA**************@TK2MSFTNGP06.phx.gbl...
>
"Chris Newby" <ch*********@rockcreekglobal.comwrote in message
news:uu**************@TK2MSFTNGP04.phx.gbl...
>I'm trying to undertand some details on the C# "lock" statement. I came
across some code during a review and thought I spotted a deadlock
scenario, but the programmer said he'd taken it from a reliable source.

Not very reliable for real :)

the Reourse property is not thread safe, the comparison should be inside
the lock statement. If not it's possible to create two instances if two
thread happen to evaluate the if before it's assigned in either thread.
NOTE that I see the DoSomethingToResource and its locking, but as the
Resource property is public you can call it from another method that do
not use the lock.

The correct wa is

lock( syncRoot )
{
if( resource == null )

{
resource = new object();
}
}

Mar 9 '07 #3
Chris Newby wrote:
Thanks Ignacio ... actually I made a mistake in the declaration. The private
field "resource" should have been declared volatile:

private static volatile object resource;

this would ensure that if one thread begins writing to "resource" any other
thread is blocked from reading it until the write operation is complete ...
correct?
No. Reads and writes to aligned, native-word-sized fields and smaller,
are atomic, but that isn't affected by volatile and the situation is
much more complicated.

Volatile affects a mental model of how reads and writes of fields work
(aka the memory model). Basically, reads can't move before of a read of
a volatile field, and nor can writes move after the write of a volatile
field. The semantics are quite mind-bending.

And these reads and writes have nothing to do with CPU caches, in case
you read that elsewhere - CPU caches have cache coherency logic which
takes care of that itself, at performance cost. Rather it can affect the
order of retiring of memory commands within the processor (very
low-level stuff) or the level of aggressiveness of compiler
optimizations permitted.

Check here for the hairy details:

http://discuss.develop.com/archives/...=DOTNET&P=R375

and more from the same author here:

http://msdn.microsoft.com/msdnmag/is...s/default.aspx

And here (the second example) is a correct implementation of the pattern
you're after:

http://blogs.msdn.com/brada/archive/...12/130935.aspx

There is a slight contradiction between these two sources for the
correctness of the first example on Brad's page. Viewing 'volatile' as
stopping writes moving after the write of a volatile field, it would
appear that having the singleton field volatile will prevent "delayed
publication" of the Singleton's private fields, if any, as initialized
in the constructor. However, Vance suggests otherwise in the first
article, but if I read the second one correctly, the fact that the field
is volatile (he refers to a "head field" in a linked list in the second
article) should prevent late publication of private fields set in the
constructor.

Technically, volatile isn't required on x86, nor the .NET 2.0 memory
model, because writes can't change order (on the same thread).

-- Barry

--
http://barrkel.blogspot.com/
Mar 9 '07 #4
On Mar 9, 3:52 pm, Barry Kelly <barry.j.ke...@gmail.comwrote:
There is a slight contradiction between these two sources for the
correctness of the first example on Brad's page. Viewing 'volatile' as
stopping writes moving after the write of a volatile field, it would
appear that having the singleton field volatile will prevent "delayed
publication" of the Singleton's private fields, if any, as initialized
in the constructor. However, Vance suggests otherwise in the first
article, but if I read the second one correctly, the fact that the field
is volatile (he refers to a "head field" in a linked list in the second
article) should prevent late publication of private fields set in the
constructor.
Vance later said that the first example in his post (the first source)
was written incorrectly. That is, that it was actually thread-safe
when the intent was the opposite. He meant to leave off the volatile
modifier.
Mar 10 '07 #5
On Mar 9, 2:29 pm, "Chris Newby" <chris.ne...@rockcreekglobal.com>
wrote:
Thanks Ignacio ... actually I made a mistake in the declaration. The private
field "resource" should have been declared volatile:

private static volatile object resource;

this would ensure that if one thread begins writing to "resource" any other
thread is blocked from reading it until the write operation is complete ...
correct?
Chris,

The volatile keyword wouldn't have made it anymore thread-safe. It
still requires that second check, hence the name double-checked
locking. Personally, I avoid these lock free strategies because
they're *incredibly* difficult to get right. Just take the lock
everytime. It's easier, safer, and faster than some think.

Brian

Mar 10 '07 #6
Brian Gideon wrote:
On Mar 9, 3:52 pm, Barry Kelly <barry.j.ke...@gmail.comwrote:
There is a slight contradiction between these two sources for the
correctness of the first example on Brad's page. Viewing 'volatile' as
stopping writes moving after the write of a volatile field, it would
appear that having the singleton field volatile will prevent "delayed
publication" of the Singleton's private fields, if any, as initialized
in the constructor. However, Vance suggests otherwise in the first
article, but if I read the second one correctly, the fact that the field
is volatile (he refers to a "head field" in a linked list in the second
article) should prevent late publication of private fields set in the
constructor.

Vance later said that the first example in his post (the first source)
was written incorrectly. That is, that it was actually thread-safe
when the intent was the opposite. He meant to leave off the volatile
modifier.
That makes sense. That mistake left me confused until I read more about
the issue in other sources, and made me even more suspicious of
lock-free code - even folks like Vance make mistakes in carefully
written expository articles :)

-- Barry

--
http://barrkel.blogspot.com/
Mar 10 '07 #7
Hi,

"Brian Gideon" <br*********@yahoo.comwrote in message
news:11**********************@c51g2000cwc.googlegr oups.com...
On Mar 9, 2:29 pm, "Chris Newby" <chris.ne...@rockcreekglobal.com>
>
The volatile keyword wouldn't have made it anymore thread-safe. It
still requires that second check, hence the name double-checked
locking. Personally, I avoid these lock free strategies because
they're *incredibly* difficult to get right. Just take the lock
everytime. It's easier, safer, and faster than some think.
I agree with you, always locking is safer and not that costly.

I do remember several threads discussing that, and somewhere I read that the
double blocking is not garanteed to work as expected.
Mar 12 '07 #8

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

Similar topics

12
by: Puvendran | last post by:
Hi, We have encountered deadlock on a table which is used to generate sequential numbers for different categories eg typical entries Category Value TRADE_NO ...
2
by: Mike | last post by:
I am trying to decipher deadlock events in a event monitor. I am trying to determine what type of lock was held. If I look at the data elements it shows LOCK MODE 5 LOCK MODE REQUESTED 3 I can...
2
by: Trent | last post by:
Hello, all. I have the following production DB2 environment. DB2 8.1.4 (fp4) WG edition with 2 production databases on Windows 2003 standard edition. My first question is regard with...
4
by: Chris | last post by:
Hello, With asynchronous programming : Why does the callback-function (running in a worker thread) may not update the state of a control on the main-form ? The docs say that you must use a...
1
by: Brian Maguire | last post by:
Can too many btree indexes cause page level locking? I read this... http://www.postgresql.org/docs/7.4/static/locking-indexes.html
14
by: Laura T. | last post by:
To synchronize thread access to shared objects, I've always used the lock(shared_object) { } pattern. I've seen many recommendations and examples where to synchronize use lock(another_object) {...
6
by: fniles | last post by:
I am using VB.NET 2003 and a socket control to receive and sending data to clients. As I receive data in 1 thread, I put it into an arraylist, and then I remove the data from arraylist and send it...
1
by: Amaxen1 | last post by:
Hello all, I have a general architecture question. We have a system that essentially does multiple processes/operations against a single table. The objective is to increase performance (i.e....
2
by: tim | last post by:
I am really new to ASP.NET and I was wondering if most developers use locking hints when accessing the data in SQL Server. What kind of multi-user issues come up when using an ASP.NET application?
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...
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
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
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...

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.