Start and stop operations in a thread-safe manner

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?

+3
source share
1 answer

What language is it in? You are right, the first version is not thread safe.

. , .

xchg-, . cmpxchg .

start() {
    if (locked_xchg(running, YES) == YES) {
        // the old value was YES, so nothing to do
        return
    }
+1

Source: https://habr.com/ru/post/1771259/


All Articles