是否可以在不使用属性的情况下创建原子局部变量?

时间:2014-05-13 01:12:13

标签: objective-c multithreading cocoa atomic

我在一个像这样的代码的方法里面

  __block NSMutableArray *myArray = [[NSMutableArray alloc] init];

  [anotherArray enumerateObjectsWithOptions:NSEnumerationConcurrent
                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

     // do some calculation and generate an object
     [myArray addObject:anObject];


  }];

因为枚举是并发的,所以当多个线程尝试将对象添加到myArray时,我遇到了崩溃。

我知道原子属性,但我想知道是否有一种方法可以在不使用属性的情况下使myArray原子和线程安全。我想保持本地化。

2 个答案:

答案 0 :(得分:3)

由于您需要对myArray进行串行访问,因此使用并发枚举可能毫无意义。但它可能取决于您在枚举中执行的操作,除了将对象添加到数组之外。

您可以同步对阵列的访问:

@synchronized(myArray) {
    [myArray addObject:anObject];
}

运行一些性能测试以查看执行上述操作实际上是否比简单地使用串行枚举更慢会很有趣,因为您不需要同步数组的开销。

答案 1 :(得分:3)

旧的C数组可能有帮助

id array[anotherArray.count];
id __strong *arrayPtr = array;

  [anotherArray enumerateObjectsWithOptions:NSEnumerationConcurrent
                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

     // do some calculation and generate an object
     arrayPtr[idx] = anObject;

  }];

 NSMutableArray *myArray = [NSMutableArray arrayWithObjects:array count:anotherArray.count];