find number of threads waiting on a resource?

D

deostroll

Hi,

Is there any way to know the number of threads waiting for a resource.
Suppose we have code like

lock(resource)
{
//...
}

Within the critical area I'd perform some logic that kind of
invalidates the reason other threads should execute the critical
region itself. Is this possible?

--deostroll
 
J

Jeroen Mostert

deostroll said:
Is there any way to know the number of threads waiting for a resource.

Not in general. You'd have to implement semantics like that yourself. You
can use Semaphore to limit the amount of waiters if you don't require an
exact count, and you can use the Interlocked class for low-overhead,
thread-safe counting (which is not necessary if you already have mutual
exclusion, by the way).
Suppose we have code like

lock(resource)
{
//...
}

Within the critical area I'd perform some logic that kind of
invalidates the reason other threads should execute the critical
region itself. Is this possible?
Yes, this is actually what monitors are all about (lock uses monitors under
the covers). The usual pattern goes like this:

lock (resource) {
while (!someConditionInvolvingResourceIsMet) Monitor.Wait(resource);
// now I know someConditionInvolvingResourceIsMet
// use resource, use Monitor.PulseAll() if others have to check their
conditions
}

What conditions people should wake up about and what they should do in
response is up to you, so it's possible to wake up other threads just to
tell them they shouldn't do anything. Of course, this also works without
explicitly waiting:

lock (resource) {
if (reasonForDoingThingsIsValid) {
...
}
}

...

lock (resource) {
invalidateReasonForDoingThings();
}

This works because you know only one thread is ever holding the lock. You
can therefore set flags for communicating with others at your leisure.

If you specifically want to avoid entering the lock altogether because you
don't want to block, use Monitor.TryEnter() explicitly, which allows you to
obtain a lock if and only if this can be done immediately (or within a
specified time):

if (Monitor.TryEnter(resource)) {
try {
// use resource
} finally {
Monitor.Exit(resource);
}
}

If you're avoiding the lock for performance reasons... well, that's a
chapter in itself and premature optimization in multithreading is the worst
premature optimization there is, so I'll assume that's not the case and keep
quiet for now to minimize the damage. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top