Hello! I have a simple class that looks a bit like this:
@protocol Recorder
@property(BOOL) isRunning;
- (void) start;
- (void) stop;
@end
And the 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, right? How about this:
- (void) start {
@synchronized(self) {
if (running)
return;
…
running = YES;
}
}
Is this correct, provided that the -stop
method is also synchronized? I don’t like the extra nesting introduced by @synchronized
, though. Would explicit lock work?
- (void) stop {
[startStopLock lock];
if (running)
return;
…
running = YES;
[startStopLock unlock];
}
Or could I do even this?
enum { Running, Stopped };
NSConditionLock *startStopLock;
- (void) start {
if (![startStopLock tryLockWithCondition:Stopped])
return;
…
[startStopLock unlockWithCondition:Running];
}
Is this solution correct? Would you do things differently?