Objective c 以线程安全的方式启动和停止操作
我有一个简单的类,看起来有点像这样:Objective c 以线程安全的方式启动和停止操作,objective-c,multithreading,thread-safety,Objective C,Multithreading,Thread Safety,我有一个简单的类,看起来有点像这样: @protocol Recorder @property(BOOL) isRunning; - (void) start; - (void) stop; @end 以及方法实现: - (void) start { if (running) return; … running = YES; } - (void) stop { if (!running) return; … ru
@protocol Recorder
@property(BOOL) isRunning;
- (void) start;
- (void) stop;
@end
以及方法实现:
- (void) start {
if (running)
return;
…
running = YES;
}
- (void) stop {
if (!running)
return;
…
running = NO;
}
我开始考虑线程安全。当前的解决方案不是线程安全的,对吗?这个怎么样:
- (void) start {
@synchronized(self) {
if (running)
return;
…
running = YES;
}
}
如果-stop
方法也同步,这是否正确?不过,我不喜欢@synchronized
引入的额外嵌套。显式锁可以工作吗
- (void) stop {
[startStopLock lock];
if (running)
return;
…
running = YES;
[startStopLock unlock];
}
或者我可以这样做吗
enum { Running, Stopped };
NSConditionLock *startStopLock;
- (void) start {
if (![startStopLock tryLockWithCondition:Stopped])
return;
…
[startStopLock unlockWithCondition:Running];
}
这个解决方案正确吗?你会用不同的方式做事吗?这是什么语言?您是正确的,第一个版本不是线程安全的 同步版本是线程安全的。对于显式锁定,您需要小心不要错过早期返回路径上的解锁 如果您有权访问锁定的xchg内部函数,那么可以通过原子交换操作相当轻松地完成。cmpxchg也可以工作
start() {
if (locked_xchg(running, YES) == YES) {
// the old value was YES, so nothing to do
return
}
这是iOS上的Objective-C。谢谢你的
locked\xchg
提示,我有OSAtomicTestAndSet
应该差不多,没问题。这是人们犯的典型错误。不幸的是,我们的Jinx产品不能在iphone上运行。否则,我建议使用它来帮助赶上这些比赛。