monitor.tryenter

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am using monitor.tryenter as follows

Do Until Monitor.TryEnter(lockLastBets, 10)
moni += 1
sendMsg("PMB std" &
Thread.CurrentThread.Name & " failed " & moni & " times", timesOther)
Loop

It appears that (occasionally?) the tryEnter doesn't relinquish control to
the other thread which is holding the lock.

I thought the whole point of TryEnter was to give a chance for the other
lock holder to finish his job and release the lock. After n failures TryEnter
returns to caller returning false. The caller can then decide what to do. I
send an error msg and go round the loop again.

Have I got it wrong?
 
gadya said:
I am using monitor.tryenter as follows

Do Until Monitor.TryEnter(lockLastBets, 10)
moni += 1
sendMsg("PMB std" &
Thread.CurrentThread.Name & " failed " & moni & " times", timesOther)
Loop

It appears that (occasionally?) the tryEnter doesn't relinquish control to
the other thread which is holding the lock.

I thought the whole point of TryEnter was to give a chance for the other
lock holder to finish his job and release the lock. After n failures
TryEnter
returns to caller returning false. The caller can then decide what to do.
I
send an error msg and go round the loop again.

Have I got it wrong?
Just call sleep when you didn't get the lock, in order to let other threads
run.

 
The point of TryEnter is to give your program the opportunity to do
something else while waiting for the lock to go away.

The TryEnter does not try repeatedly to get a lock. If the object is
locked it returns immediately so that your program can make use of the time.

Unless you have a multi processor machine, there is only one thread
running at any time. That means that if the object is locked when your
thread is running, it won't be unlocked until your time slice is over,
and the thread holding the lock gets a chance to finish what it was
doing when locking the object. This in turn means that if you have a
loop what waits for the lock to go away and don't do anything worth wile
in the loop, you will waste your entire time slice waiting for something
that can not happen.

If you are not going to do something while waiting for the lock, use the
Enter method, or at least call Thread.Sleep to give up the rest of the
time slice to other processes.
 
Back
Top