Re: Multi-threading article finally "finished" - reviewers welcome

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 06/28/04


Date: Mon, 28 Jun 2004 17:26:27 +0100

William Stacey [MVP] <staceywREMOVE@mvps.org> wrote:
> > Only if someCollection.SyncRoot==someCollection in this case. Why bring
> > that possibility into things?
>
> Sorry, not following you. This is possible deadlock regardless if locking
> on "this" or another object.
> T1
> lock(somethingElse)
> {
> lock(obj.SyncRoot) // or "this"
> {
> }
> }
>
> T2
> lock(obj.SyncRoot) // or "this"
> {
> lock(somethingElse)
> {
> }
> }

That's not the code I posted though. I posted:

<quote>
lock (someCollection)
{
    lock (somethingElse)
    {
         ...
    }
}

Another thread does:

lock (somethingElse)
{
    lock (someCollection.SyncRoot)
    {
         ...
    }
}
</quote>

If obj and obj.SyncRoot are different references, there's no dead-lock
in the above code.
 
> > Using independent locks makes it a lot
> > cleaner, IMO.
>
> "this" is independent. Moreover, if you add a 1000 objects that contain
> syncRoot objects, you add almost 8K of memory for just the seperate lock
> objects(assuming 8 bytes, could be more or less. Sure someone will let me
> know.) This may not be much for some folks, but is it is not a trivial
> amount of memory.

Well, you've already got *at least* that much memory anyway for the
other objects - and chances are those objects are going to be doing
something useful, especially if they're collections. If you've got a
thousand totally empty collections (which last beyond gen0) I suspect
you're in an unusual situation. (Collections tend to have a bit of
buffer space left over most of the time - do you call
ArrayList.TrimToSize on every ArrayList you create?)

I'd rather have code which was easy to maintain at the cost of a few K
of memory here and there than unmaintainable but efficient code.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages