1

在Objective-C中,我们知道@synchronized可以用来定义临界区,但是有没有办法知道多个线程是否在访问一个方法或代码块呢?

4

1 回答 1

1

您可以使用一个NSLock对象(参考)并使用以下方法测试锁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
于 2013-02-01T12:53:24.923 回答