I have a simple class that looks something like this:
@protocol Recorder
@property(BOOL) isRunning;
- (void) start;
- (void) stop;
@end
And method implementations:
- (void) start {
if (running)
return;
…
running = YES;
}
- (void) stop {
if (!running)
return;
…
running = NO;
}
And I started thinking about thread safety. The current solution is not thread safe, is it? How about this:
- (void) start {
@synchronized(self) {
if (running)
return;
…
running = YES;
}
}
Is this correct if the method is -stopalso synchronized? I do not like the additional investment introduced @synchronized. Will explicit blocking work?
- (void) stop {
[startStopLock lock];
if (running)
return;
…
running = YES;
[startStopLock unlock];
}
Or could I do this?
enum { Running, Stopped };
NSConditionLock *startStopLock;
- (void) start {
if (![startStopLock tryLockWithCondition:Stopped])
return;
…
[startStopLock unlockWithCondition:Running];
}
Is this the right decision? Could you do otherwise?
source
share