473,405 Members | 2,171 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,405 software developers and data experts.

what's wrong with lock(this) ?

I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.

Pros and cons?

-KJ
Nov 16 '05 #1
6 10027
n_**********@mail.com (n_o_s_p_a__m) wrote in
news:1f**************************@posting.google.c om:
I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.

Pros and cons?


lock() is most of the time used as a semaphore for a critical
action. To prevent multiple threads entering the same codeblock, an object
is locked (the parameter to lock()). THe bigger the object, the more time
it costs to lock it. So if you just want to prevent multiple threads
entering a codeblock, you'd better do this:

object uniqueObject = new object();

lock(uniqueObject)
{
// your code
}

Frans.

--
Get LLBLGen Pro, the new O/R mapper for .NET: http://www.llblgen.com
My .NET Blog: http://weblogs.asp.net/fbouma
Microsoft C# MVP
Nov 16 '05 #2
Frans Bouma [C# MVP] <pe******************@xs4all.nl> wrote:
n_**********@mail.com (n_o_s_p_a__m) wrote in
news:1f**************************@posting.google.c om:
I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.

Pros and cons?


lock() is most of the time used as a semaphore for a critical
action. To prevent multiple threads entering the same codeblock, an object
is locked (the parameter to lock()). THe bigger the object, the more time
it costs to lock it. So if you just want to prevent multiple threads
entering a codeblock, you'd better do this:

object uniqueObject = new object();

lock(uniqueObject)
{
// your code
}


While I agree with the idea of using a separate object, I disagree with
your reasoning. In particular, I don't know of anything which makes it
slower to lock a bigger object.

The main reason (IMO) for avoiding locking on "this" is in case other
classes are locking on the same reference. As soon as you lock on a
reference which other classes have access to, you're at the whim of
what those classes will be doing in terms of deadlocking etc. If you
only ever lock on references which are only available within your own
class, you get a lot more control. You can also have different locks
separate "partitions" of exclusion.

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

"Frans Bouma [C# MVP]" <pe******************@xs4all.nl> wrote in message
news:Xn********************************@207.46.248 .16...
n_**********@mail.com (n_o_s_p_a__m) wrote in
news:1f**************************@posting.google.c om:
I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.

Pros and cons?
lock() is most of the time used as a semaphore for a critical
action. To prevent multiple threads entering the same codeblock, an object
is locked (the parameter to lock()). THe bigger the object, the more time
it costs to lock it. So if you just want to prevent multiple threads
entering a codeblock, you'd better do this:


I don't think thats entirely correct. Nothing I have seen suggests that
lock\Monitor has any issue with object size. Instead Monitor basically uses
a small SyncBlock which is associated with the object on the fly. the
parameter passed to lock\Monitor.Enter() is simply the one which has the
associated SyncBlock so that further calls to lock\Monitor.Enter() can find
that block and handle it. I think the block is disassociated when all lock
blocks end(this is mostly based on my own examiniation of rotor and Jeffery
Richter's column Safe Thread Synchronization[1], so I could easily be
wrong).

I would be interested if you happen to have information as to why object
size matters, however.

The more important reason, IMHO, not to lock on this is that this is
available to other objects. If you have a method that locks on this, a
method in another object(on a different thread) could easily call
lock(myObjectInstanceVariable), thereby creating a potential deadlock in a
very unrelated piece of code. Anytime you perform a lock on a value that is
available to the outside you run the risk of it being locked by code outside
of your control and introducing a deadlock.

1. http://msdn.microsoft.com/msdnmag/issues/03/01/NET/

object uniqueObject = new object();

lock(uniqueObject)
{
// your code
}

Frans.

--
Get LLBLGen Pro, the new O/R mapper for .NET: http://www.llblgen.com
My .NET Blog: http://weblogs.asp.net/fbouma
Microsoft C# MVP

Nov 16 '05 #4
Frans,
its not really that it costs mroe to lock bigger objects its to
prevent deadlocks with opened monitors on the object and the finalizers,
in the case that the monitor never exits before the object is ready for
finalization
HTH

Frans Bouma [C# MVP] wrote:
n_**********@mail.com (n_o_s_p_a__m) wrote in
news:1f**************************@posting.google.c om:

I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.

Pros and cons?

lock() is most of the time used as a semaphore for a critical
action. To prevent multiple threads entering the same codeblock, an object
is locked (the parameter to lock()). THe bigger the object, the more time
it costs to lock it. So if you just want to prevent multiple threads
entering a codeblock, you'd better do this:

object uniqueObject = new object();

lock(uniqueObject)
{
// your code
}

Frans.


--
Regards,
Dilip Krishnan
MCAD, MCSD.net
dilipdotnet at apdiya dot com
Nov 16 '05 #5
n_o_s_p_a__m wrote:
I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.

Pros and cons?


I haven't seen any major arguments about lock( this) - the only problem
I see with it is that the lock potentially has a larger 'granularity'
than might really be needed.

For example, if an object contains an internal cache and some other
value that is unrelated to the cache, and both the cache and the value
can be updated in multiple threads, there's probably no reason to lock
on the entire object when updating the cache - you can lock on the cache
alone.

However, I have seen some discussion on the "lock( typeof( ClassName))"
idiom, indicating that it should not be used (even though it is used in
many Microsoft samples). See:

http://msdn.microsoft.com/library/en...ui06032003.asp

--
mikeb
Nov 16 '05 #6
mikeb <ma************@nospam.mailnull.com> wrote:
However, I have seen some discussion on the "lock( typeof( ClassName))"
idiom, indicating that it should not be used (even though it is used in
many Microsoft samples). See:

http://msdn.microsoft.com/library/en...ui06032003.asp


The same arguments presented apply to "this" as well:

<quote>
The basic problem here is that you don't own the type object, and you
don't know who else could access it. In general, it's a very bad idea
to rely on locking an object you didn't create and don't know who else
might be accessing. Doing so invites deadlock. The safest way is to
only lock private objects.
</quote>

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

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

Similar topics

3
by: andrew | last post by:
Ok, pretty new to this php stuff, but good with perl/python etc. What is wrong with this php document ??? I get this error: Parse error: syntax error, unexpected $end in...
6
by: Oli | last post by:
Hi What's wrong with this? sql="insert into tblNumbers (Number) values ('" & i & "')" I get... Error Type: Microsoft JET Database Engine (0x80040E14) Syntax error in INSERT INTO statement.
1
by: learningGuy | last post by:
Can someone tell me what is wrong with this simple code? I get an exception every time at the myFile.Open() line. I have included the code that I think is needed to for you to answer this below:...
9
by: datastructure | last post by:
Copyright (c) 2003 by James J. Perry. All Rights Reserved. char Square::validList = {'r', 'g', 'b'}; //missing an element, is 0 int Square::numValues = 3; Square::Square() { value =...
6
by: neo88 | last post by:
hi guys Can anyone please tell me what is wrong with this function: inline int strength(void) { int a; // tests to see what strength value the agent just attacked\defended with for (strength;...
6
by: Niklaus | last post by:
Hi, Can someone point out what is wrong with this code ? How can i make it better optimize it. When run it gives me seg fault in linux. But windows it works fine(runs for a long time). Do we...
10
by: Protoman | last post by:
Could you tell me what's wrong with this program, it doesn't compile: #include <iostream> #include <cstdlib> using namespace std; class Everything { public: static Everything* Instance()
1
by: objectmodelol | last post by:
I just switched from MS SQL 2000/2005 to MySql. What's wrong with this stored procedure: DELIMITER $$ DROP PROCEDURE IF EXISTS `listing`.`SaveUser` $$ CREATE DEFINER=`root`@`localhost`...
6
by: CTG | last post by:
"update set UPDATE-FLAG=false, UPDATE-DT= '10/09/2007 4:09:59 PM' WHERE ICCID='I1' " UPDATE_FLAG is a YES/NO ICCID is TEXT I have tried YES, NO as well but still fails,
4
by: hirsh.dan | last post by:
i have a functions that writes information to a file. inside that function i have a line in which i call another function. if this line is executed, nothing is written to the file, but if i remark...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
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
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...
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...
0
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...

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.