473,542 Members | 2,049 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Locking techniques

To synchronize thread access to shared objects, I've always used the
lock(shared_obj ect) { } pattern.
I've seen many recommendations and examples where to synchronize use
lock(another_ob ject) { use shared_object; } pattern.

I do not see any reason to have another simple object to lock for since I
can lock the shared object directly.

Are there any deep implications to use shared lock object to guard the
actual shared object, maybe performance oriented?
Which is better, if it can be measured?
TIA,

LT
Nov 30 '05 #1
14 1347
Hi LT,

A recommendation to use the latter approach [lock(another_ob ject)] is
because your code controls who and when locks are applied to to this
object. In the first case, a rogue client may obtain and keep a lock
to the shared_object preventing the other threads from accessing it.

I'm not sure if there is some code deep down in the CLR that would
impact performance and somehow I don't think so. But the latter
approach uses one more object a little more memory than the first.

In my opinion, if you are writing your own application and the
shared_object is a private object, ie no one can access it outside
you're code, then you'll be quite fine using the first approach.

In short, the second approach is safer and less error prone but uses a
bit more memory.

Cheers,
Adam
-------------------------------------------------------------------------------------------
J-Integra Interoperabilit y Solutions
http://j-integra.intrinsyc.com/
high performance interop middleware for java, corba, com & .net

Nov 30 '05 #2
Hi Adam,

For me the first approach lock(shared_obj ect) seemed better since I do not
need to lookup which object guards which. It's easier to remember to lock
the object I need to operate really than to lookup which guard object guards
what. And it makes locking more granular automatically because the
another_object could be used (wrongly) to guard other uses also.
I was more concerned if there could be some CLR internals that makes the
first apporach more inefficient or "dangerous" .

Thanks,

LT

"Adam Cooper" <ad*********@gm ail.com> ha scritto nel messaggio
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
Hi LT,

A recommendation to use the latter approach [lock(another_ob ject)] is
because your code controls who and when locks are applied to to this
object. In the first case, a rogue client may obtain and keep a lock
to the shared_object preventing the other threads from accessing it.

I'm not sure if there is some code deep down in the CLR that would
impact performance and somehow I don't think so. But the latter
approach uses one more object a little more memory than the first.

In my opinion, if you are writing your own application and the
shared_object is a private object, ie no one can access it outside
you're code, then you'll be quite fine using the first approach.

In short, the second approach is safer and less error prone but uses a
bit more memory.

Cheers,
Adam
-------------------------------------------------------------------------------------------
J-Integra Interoperabilit y Solutions
http://j-integra.intrinsyc.com/
high performance interop middleware for java, corba, com & .net

Dec 1 '05 #3

"Adam Cooper" <ad*********@gm ail.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
Hi LT,

A recommendation to use the latter approach [lock(another_ob ject)] is
because your code controls who and when locks are applied to to this
object. In the first case, a rogue client may obtain and keep a lock
to the shared_object preventing the other threads from accessing it.

I'm not sure if there is some code deep down in the CLR that would
impact performance and somehow I don't think so. But the latter
approach uses one more object a little more memory than the first.

In my opinion, if you are writing your own application and the
shared_object is a private object, ie no one can access it outside
you're code, then you'll be quite fine using the first approach.

In short, the second approach is safer and less error prone but uses a
bit more memory.

Cheers,
Adam


Also, as Singletons are often implemented with static members and methods
there are no 'this' to lock on. Hence, a lock object are needed.

Happy Coding
- Michael S
Dec 1 '05 #4
Michael S wrote:

<snip>
Also, as Singletons are often implemented with static members and methods
there are no 'this' to lock on. Hence, a lock object are needed.


In those cases, typeof(Singleto n) is often used to lock on - which is
just as bad as locking on "this".

Jon

Dec 1 '05 #5
Laura T. wrote:
For me the first approach lock(shared_obj ect) seemed better since I do not
need to lookup which object guards which.
If you don't have a *very* clear understanding about what needs to be
locked in what circumstances, you *will* run into problems.
It's easier to remember to lock
the object I need to operate really than to lookup which guard object guards
what. And it makes locking more granular automatically because the
another_object could be used (wrongly) to guard other uses also.
I was more concerned if there could be some CLR internals that makes the
first apporach more inefficient or "dangerous" .


It's dangerous because if you lock on an object and some code within
the implementation of that object decides to lock on itself in another
thread, you could easily run into deadlocks when you didn't need to
have any contention in the first place.

Furthermore, if you take out locks without a clearly documented order,
you can easily deadlock even within a single class.

It sounds like you're really trying to get away from properly analysing
where you need to synchronize which resources. That's very dangerous.

See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more
information.

Jon

Dec 1 '05 #6
Is the URL correct? I get 404

Marc

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Laura T. wrote:
For me the first approach lock(shared_obj ect) seemed better since I do
not
need to lookup which object guards which.


If you don't have a *very* clear understanding about what needs to be
locked in what circumstances, you *will* run into problems.
It's easier to remember to lock
the object I need to operate really than to lookup which guard object
guards
what. And it makes locking more granular automatically because the
another_object could be used (wrongly) to guard other uses also.
I was more concerned if there could be some CLR internals that makes the
first apporach more inefficient or "dangerous" .


It's dangerous because if you lock on an object and some code within
the implementation of that object decides to lock on itself in another
thread, you could easily run into deadlocks when you didn't need to
have any contention in the first place.

Furthermore, if you take out locks without a clearly documented order,
you can easily deadlock even within a single class.

It sounds like you're really trying to get away from properly analysing
where you need to synchronize which resources. That's very dangerous.

See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more
information.

Jon

Dec 1 '05 #7
Hi Jo,

it's not that I don't have a *very* clear understanding. To have a very
clear understanding, the rules (and parameters) must be as simple as
possibile. Thus, a rule "access to a shared x needs lock of x" seems quite
simple and clear, easier to implement than "access to shared x needs lock
y".

And yes, I agree with you for dangerous, to some extent, but as far as I go,
lock(this) is not even an issue. All objects involved are under our control.
Deadlocks can happen, granted. The simpler the rules, the simpler the lock
ordering will be to avoid catches.

Thanks!

LT

"Jon Skeet [C# MVP]" <sk***@pobox.co m> ha scritto nel messaggio
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Laura T. wrote:
For me the first approach lock(shared_obj ect) seemed better since I do
not
need to lookup which object guards which.


If you don't have a *very* clear understanding about what needs to be
locked in what circumstances, you *will* run into problems.
It's easier to remember to lock
the object I need to operate really than to lookup which guard object
guards
what. And it makes locking more granular automatically because the
another_object could be used (wrongly) to guard other uses also.
I was more concerned if there could be some CLR internals that makes the
first apporach more inefficient or "dangerous" .


It's dangerous because if you lock on an object and some code within
the implementation of that object decides to lock on itself in another
thread, you could easily run into deadlocks when you didn't need to
have any contention in the first place.

Furthermore, if you take out locks without a clearly documented order,
you can easily deadlock even within a single class.

It sounds like you're really trying to get away from properly analysing
where you need to synchronize which resources. That's very dangerous.

See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more
information.

Jon

Dec 1 '05 #8
There is a MSR publication that seems to approve the use of lock(this) in
many cases.

http://research.microsoft.com/resear...aspx?tr_id=921

LT

"Jon Skeet [C# MVP]" <sk***@pobox.co m> ha scritto nel messaggio
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Michael S wrote:

<snip>
Also, as Singletons are often implemented with static members and methods
there are no 'this' to lock on. Hence, a lock object are needed.


In those cases, typeof(Singleto n) is often used to lock on - which is
just as bad as locking on "this".

Jon

Dec 1 '05 #9
Laura T. wrote:
There is a MSR publication that seems to approve the use of lock(this) in
many cases.

http://research.microsoft.com/resear...aspx?tr_id=921


Interesting that it doesn't really go into *why* that's being used
though - it seems to be used pretty much by default, ignoring the
possibility that other code will lock on the same reference.

I'm sure there are plenty of articles which use lock(this) - but there
are also articles which describe the pitfalls of such an approach.
Here's one by Jeffrey Richter:

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

Personally I think it was a mistake making all reference types have
monitors - although it's taken me a long time to come to that
conclusion. (I used to think it was a great idea, right back from when
I started Java programming.)

See http://www.pobox.com/~skeet/csharp/t...ernative.shtml for a
view on how I would have preferred things to work - and an option for
coding that way instead of using plain "lock" statements.

Jon

Dec 1 '05 #10

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

Similar topics

4
4500
by: Michael Chermside | last post by:
Ype writes: > For the namespaces in Jython this 'Python internal thread safety' > is handled by the Java class: > > http://www.jython.org/docs/javadoc/org/python/core/PyStringMap.html > > which has almost all of it public methods Java synchronized: > > http://cvs.sourceforge.net/viewcvs.py/jython/jython/org/python/core/PyStringMap.
12
9541
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 1456 JOB_NO 267 .....
16
8902
by: Nid | last post by:
How do I do row-level locking on SQL Server? Thanks, Nid
10
11867
by: McFly Racing | last post by:
Thread Locking In Static Methods I have the need for a Log Manger class that has static methods. Normally I would use the lock statement or a Monitor statement both of which take a reference to (this). In the case of these static methods I am not able to do that.
15
6163
by: z. f. | last post by:
Hi, i have an ASP.NET project that is using a (Class Library Project) VB.NET DLL. for some reason after running some pages on the web server, and trying to compile the Class Library DLL, it can't compile because the DLL is in use (and the PDB too), and the w3wp.exe process is the process locking the DLL (as viewed with Sysinternals - Process...
7
2843
by: Shak | last post by:
Hi all, I'm trying to write a thread-safe async method to send a message of the form (type)(contents). My model is as follows: private void SendMessage(int type, string message) { //lets send the messagetype via async NetworkStream ns = client.GetStream(); //assume client globally accessible
0
1313
by: xpding | last post by:
Hello, I have a class MyEmbededList contains a generic dictionary, the value field is actually the MyEmbededList type as well. There is another class need to access and manipulate a list of MyEmbededList (please refer to the MyTestClass below). I am not sure whether I implements the right locking mechanism here and hope someone can give me...
0
4089
by: Cindy Huyser | last post by:
I have an Access 2000 database behind a threaded Java application that that can have have concurrent access to the same table (but not the same record). The database is set up for shared access with "No locks" as the default, so that optimistic record locking should take place, and "Open databases using record-level locking" is selected. Each...
1
2218
by: Paul H | last post by:
I have an Employees table with the following fields: EmployeeID SupervisorID Fred Bob Bob John Bob Mary Bill Bill I have created a self join in the relationships window, with
0
7392
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...
0
7330
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...
0
7571
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. ...
0
7670
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5246
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...
0
3380
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...
0
3376
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1798
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
943
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.