discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

NSConditionLock


From: Thomas Davie
Subject: NSConditionLock
Date: Mon, 12 Dec 2011 15:20:13 +0000

Hi all,

I may be misunderstanding what NSConditionLock is supposed to do here, so please correct me if I'm talking rubbish.  Apple's docs state for lockWhenCondition: "The receiver’s condition must be equal to condition before the locking operation will succeed. This method blocks the thread’s execution until the lock can be acquired.".

The way I read this is that while the thread making the call should block, other threads attempting to access the lock while the condition is not met should not block.

Here's GNUstep's implementation:
- (void) lockWhenCondition: (NSInteger)value
{
  [_condition lock];
  while (value != _condition_value)
    {
      [_condition wait];
    }
}

I'm pretty sure this doesn't match the right semantics if:

The lock is initialised with a condition that isn't 5
Thread 1 calls [lock lockWhenCondition:5];
Thread 2 calls [lock lock];
Thread 2 calls [lock unlockWithCondition:5];

My expectation here would be for thread 1 to block at it's call to lockWhenCondition:, then for thread 2 to acquire the lock, then for it to give up the lock, and for thread 1 to unblock.

The actual results with GNUstep's implementation are for thread 1 to not get the lock, but for it to become locked, then for thread 2 to block because thread 1 has the lock, and for the program to deadlock.

Wouldn't an implementation more like this be appropriate (note though that this too is buggy as it violate's NSCondition's API contract that wait must only be called while locked)?

- (void) lockWhenCondition: (NSInteger)value
{
  while (1)
  {
    [_condition lock];
    if (value != _condition_value)
    {
      return;
    }
    [_condition unlock];
    [_condition wait];
  }
}

Thanks

Tom Davie

reply via email to

[Prev in Thread] Current Thread [Next in Thread]