NSLock, number of threads waiting

633 Views Asked by At

I'm developing an iOS app and need to implement a solution for a problem for which I need to know how many threads are waiting for locking the same NSLock object.

In Java I have the class ReentrantLock, with the method getQueueLength, which "Returns an estimate of the number of threads waiting to acquire this lock."

Is there something similar in Objective-C? I've tried to find something, but nothing. Should I subclass NSLock for implementing this mechanism by myself?

2

There are 2 best solutions below

0
On

Look at OSAtomic.h. You can create a global counter, then before a thread tries to get the lock increment it, then decrement afterwards. To read the current value you "add" 0 to it and look at the return value. I have used these for years on both OSX and ios.

0
On

You can create a subclass of NSLock with the same functionality by overriding the lock, unlock and tryLock methods.

Example:

@interface ReentrantLock : NSLock

@property (atomic) NSInteger numberOfThreads;

- (void)lock;
- (void)unlock;
- (BOOL)tryLock;

@end

@implementation ReentrantLock

- (void)lock {
    self.numberOfThreads += 1;
    [super lock];
}

- (void)unlock {
    self.numberOfThreads -= 1;
    [super unlock];
}

- (BOOL)tryLock {
    self.numberOfThreads += 1;
    return [super tryLock];
}

@end