Another locking question.

  • Thread starter Thread starter Cool Guy
  • Start date Start date
C

Cool Guy

Is it possible to lock on one object from several threads at a time? If
so, is the order in which it "unlocks" the same as the order in which it
locks?

e.g.:

lock from thread1;
lock from thread2;
lock from thread3;
unlock from thread3;
unlock from thread2;
unlock from thread1;

Is this what would happen if we locked from three threads in the
illustrated order?
 
Niki said:
No, that's the whole sense of locking: to prevent two or more threads from
accessing the same resource at the same time. If one thread tries to acquire
a lock on an object that is already locked, lock() will wait until the other
thread leaves the lock-block.

Bad phrasing on my part.

Here's a better example:

thread1 locks;
thread2 tries to lock but fails;
thread3 tries to lock but fails;

Once thread1 has unlocked, I presume that thread2 will lock it, then after
thread2 has unlocked, thread3 will lock it, and so on. Is this correct?
 
Cool Guy said:
Is it possible to lock on one object from several threads at a time?

No, that's the whole sense of locking: to prevent two or more threads from
accessing the same resource at the same time. If one thread tries to acquire
a lock on an object that is already locked, lock() will wait until the other
thread leaves the lock-block.

Niki
 
Hi Cool Guy,

I'm not entirely certain of this, but I think you have no way of knowing which of the waiting threads aquires the lock after it is released. Thread 2 and thread 3 have equal priority in aquiring the lock, and thread 3 might get the lock before thread 2.
 
From testing this out a while back:

if the other threads are of equal priority they appear to aquire the lock in
teh order they requested it (I haven't see this *documented* anywhere so I
wouldn't base my system on this behavior).

If Thread 3 has a higher priority than Thread 2 it will acquire the lock
first (at least this was the behavior I observed) irrespective of the order
the two threads attempted to acquire the lock - which is how it should be

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richard/weblog
 
Back
Top