I've got an Objective-c app with several blocks of code where I only want one thread to be able to access it at a time. Using a @synchronized(self) block works fine for that.
However, I've got one block where I want it to skip the block, if another thread is in one of the @synchronized blocks, rather than wait. Is there a way to simply test if self (or whatever my lock object is) is being held by another synchronized block?
// block 1 - wait until lock is available
@synchronized(self) {
...
}
...
// block 2 - wait until lock is available
@synchronized(self) {
...
}
...
// block 3 - wait until lock is available
@synchronized(self) {
...
}
...
// block 4 - skip if lock is not immediately available - no waiting!
howDoISkipIfLockIsNotAvailable(self) {
...
}
What you want to achieve is possible when using NSLock or NSRecursiveLock instead of the @synchronized syntax sugar. They key feature it offers is the tryLock method:
NSRecursiveLock *lock = [[NSRecursiveLock alloc] init];
[lock lock];
@try {
// ... do synchronized stuff
}
@finally {
[lock unlock];
}
if ([lock tryLock]) {
@try {
// do synchronized stuff if possible
}
@finally {
[lock unlock];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With