Reputation: 41510
In Objective-C, we know that @synchronized can be used to define a critical section, but is there a way to know if multiple threads are accessing a method or code block?
Upvotes: 1
Views: 310
Reputation: 122458
You could use an NSLock
object (reference) and test the lock using tryLock
:
@interface MyObject : NSObject
{
NSLock *_lock;
}
...
@end
@implementation MyObject
- (id)init
{
...
_lock = [[NSLock alloc] init];
...
}
- (BOOL)myMethod
{
if (![_lock tryLock])
{
NSLog(@"Failed to acquire lock");
return NO;
}
// Thread has exclusive access
// Caution; the lock won't be automatically unlocked if this method throws an exception
// so add some exception handling here to ensure it's always unlocked...
@try
{
// Do stuff
}
@finally
{
[_lock unlock];
}
return YES;
}
@end
Upvotes: 1