gpt4 book ai didi

ios - @synchronized() 接受的参数是什么

转载 作者:可可西里 更新时间:2023-11-01 04:23:30 25 4
gpt4 key购买 nike

我知道@synchronized() 的作用,但是...
有时我们有:

1- @synchronized(self)
2- @synchronized([MyClass 类])
3- @synchrinized(myObj)

有什么区别,我应该传递给这个 block 的参数是什么?

最佳答案

来自documentation :

The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block. If you execute the preceding method in two different threads, passing a different object for the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. If you pass the same object in both cases, however, one of the threads would acquire the lock first and the other would block until the first thread completed the critical section.

所以这取决于你想保护什么不被同时执行,并且这三种情况都有应用。

例如,在

-(void)addToMyArray1:(id)obj
{
@synchronized(self) {
[self.myArray1 addObject:obj];
}
}

-(void)addToMyArray2:(id)obj
{
@synchronized(self) {
[self.myArray2 addObject:obj];
}
}

两个@synchronized block 不能被两个线程调用同时执行同一实例(self)上的方法,从而保护对来自不同线程的数组。

但它也阻止了第一种方法的阻塞与第二种方法中的 block 同时执行,因为它们使用相同的锁 self。因此,对于更细粒度的锁定,您可以使用不同的锁:

-(void)addToMyArray1:(id)obj
{
@synchronized(self.myArray1) {
[self.myArray1 addObject:obj];
}
}

-(void)addToMyArray2:(id)obj
{
@synchronized(self.myArray2) {
[self.myArray2 addObject:obj];
}
}

现在从不同线程同时访问 self.myArray1self.myArray2仍然受到保护,但彼此独立。

上的锁可用于保护对全局变量的访问。这只是一个用于演示目的的简单示例:

static int numberOfInstances = 0;

-(id)init
{
self = [super init];
if (self) {
@synchronized([self class]) {
numberOfInstances++;
}
}
}

关于ios - @synchronized() 接受的参数是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22478708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com