阻止@synchronized
在 @synchronized 内执行块似乎会取消锁定。
- (void)method {
@synchronized(self) {
if(ivar == nil) {
ivar = [myBlock() retain];
}
}
}
实例变量ivar
未写入任何其他位置。
我观察到块 myBlock
有时在我的应用程序中执行两次。
怎么会发生这种事呢?如何避免这种情况并进行真正的工作锁定?
Executing a block inside @synchronized
seems to negate the lock.
- (void)method {
@synchronized(self) {
if(ivar == nil) {
ivar = [myBlock() retain];
}
}
}
The instance variable ivar
is not written in any other location.
I've observed that the block myBlock
sometimes is executed twice in my application.
How can this ever happen? How to avoid this an do a real working lock?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许你可以移动块内的锁。
Maybe you could move the locking inside the block.
该锁工作正常,因为
synchronized
仅锁定线程,并且同一线程访问该区域两次。问题是,myBlock
在某些情况下会在内部执行自身。The lock worked fine as
synchronized
locks only threads, and the same thread was accessing the region twice. The problem was, thatmyBlock
executed itself inside under some circumstances.