Threads in C#

  • Thread starter Thread starter Luk Vloemans
  • Start date Start date
L

Luk Vloemans

Hey,

Having a few problems using threads in C#. In the msdn documentation,
mutual exclusion is only discussed when dealing with threads that all
execute the same method.

What's the actual meaning of the lock function?

All I want to do is keep other threads from entering their critical
sections when one of the threads is its critical section.

The critical sections are different though, they are not located inside
the same method.

Any help please?

Thanks in advance,

Luk Vloemans
 
Luk,

lock can be applied to any reference object (i.e. to objects of classes, not
of structs). The simplest way to use it is usually lock (this).

class X
{
func a ()
{
lock (this)
{
// do stuff
}
}

func b ()
{
lock (this)
{
// do stuff
}
}
}

Since both a and b lock on the same things, then one thread entering a
excludes others from entering b (as well as a). Note that this is per object
locking. Do do per class locking you'd have to lock on a static member.

More refined locking can be done by locking on a specific object:

class X
{
string aData;
string bData;

func a ()
{
lock (aData)
{
// manipulate aData
}
}

func b ()
{
lock (bData)
{
// manipulate bData
}
}
}

If you one broader locking, then you just need to share some object between
all the objects involved and lock on that in your various methods:

Regards,

Jasper Kent.
 
Jasper Kent said:
lock can be applied to any reference object (i.e. to objects of classes, not
of structs). The simplest way to use it is usually lock (this).

I would strongly recommend *not* locking on this. Instead, lock on a
private reference which *only* the class itself can see; you can also
have various locks for if you want to lock in different circumstances
(for instance, lock all method calls to A against each other, and all
method calls to B against each other, but you can have one of each of A
and B running at the same time). This way you can make the lock
variable name descriptive of *exactly* its purpose, and because no
other code will have a reference to what you're locking, they can't end
up locking on the same thing and causing problems.

In the rare occasions where you need multiple classes to lock on the
same reference, again I'd suggest creating a separate object just for
the purpose of locking.
 
Back
Top