简体   繁体   English

iOS Objective-c同步

[英]iOS Objective-c synchronized

In Java if I have the keyword synchronized in a method, it will prevent being executed by more than one thread at same time, no matter what thread is: 在Java中,如果我在一个方法中同步了关键字,那么无论哪个线程,它都将阻止多个线程同时执行:

public synchronized void doSomething() {
  //synchronous code here
}

In objective-c if do this, will I have the same result? 在Objective-C中,如果这样做,结果是否相同?

-(void)doSomething{
    @synchronized (self) {
       //synchonous code here
    }
}

Yes, with a caveat. 是的,请注意。

The @synchronized directive creates a mutex lock—preventing the code within the curly brackets from being executed by different threads at the same time. @synchronized指令创建一个互斥锁-防止大括号内的代码同时由不同线程执行。 The caveat is that it uses the object that was passed to it as a unique identifier to distinguish the protected block. 需要注意的是,它使用传递给它的对象作为唯一标识符来区分受保护的块。 So if you're using @synchronized(self) in two different methods, those two methods are prevented from being executed by different threads at the same time (because they share the same identifier (in this case self )). 因此,如果您在两种不同的方法中使用@synchronized(self) ,则会阻止这两种方法同时由不同的线程执行(因为它们共享相同的标识符(在本例中为self ))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM