Copyright ã1994 by NeXT Computer, Inc.  All Rights Reserved.

NSConditionLock 

Inherits From:	NSObject

Conforms To:	NSLocking
NSObject (NSObject)

Declared In:	Foundation/NSLock.h 

Class Description

NSConditionLock objects are used to lock and unlock threads when specified conditions occur.

The user of an NSConditionLock object can lock when a process enters a particular state and can set the state to something else when releasing the lock. The states are defined by the lock's user. NSConditionLock is well suited to synchronizing different modules such as a producer and a consumer where the two modules must share data, but the consumer must sleep until a condition is met such as more data being available.

The NSConditionLock class provides four ways of locking its objects (lock, lockWhenCondition:, tryLock, and tryLockWhenCondition) and two ways of unlocking (unlock and unlockWithCondition:). Any combination of locking method and unlocking method is legal. 

The following example shows how the producer-consumer problem might be handled using condition locks. The producer need not wait for a condition, but must wait for the lock to be made available so it can safely create shared data. For example, a producer could use a lock this way:

/* create the lock only once */
id condLock = [NSConditionLock new];

[condLock lock];
/* Manipulate global data... */
[condLock unlockWithCondition:HAS_DATA];

Multiple consumer threads can then lock until there's data available and everyone is out of locked critical sections. In the following code sample, the consumer sleeps until the producer invokes unlockWithCondition: with the parameter HAS_DATA:

[condLock lockWhenCondition:HAS_DATA];
/* Manipulate global data if necessary... */
[condLock unlockWithCondition:(moreData ? HAS_DATA : NO_DATA)];

An NSConditionLock object doesn't busy-wait, so it can be used to lock time-consuming operations without degrading system performance.

The NSConditionLock, NSLock, and NSRecursiveLock classes all implement the NSLocking protocol with various features and performance characteristics; see the other class descriptions for more information.

Initializing an NSConditionLock

- (id)initWithCondition:(int)condition	Initializes a newly created NSConditionLock and sets its condition to condition.

Returning the Condition

- (int)condition	Returns the receiver's condition, the state that must be achieved before a conditional lock can be acquired or released.

Acquiring and Releasing a Lock

- (void)lockWhenCondition:(int)condition	Attempts to acquire a lock when condition is met. Blocks until condition is met.

- (void)unlockWithCondition:(int)condition	Releases the lock and sets lock state to condition.

- (BOOL)tryLock	Attempts to acquire a lock. Returns YES if successful and NO otherwise.

- (BOOL)tryLockWhenCondition:(int)condition	Attempts to acquire a lock when condition is met. Returns YES if successful and NO otherwise.