NSMutableArray线程安全 [英] NSMutableArray thread safety

查看:346
本文介绍了NSMutableArray线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在访问并更改多个线程中的可变数组。开始时,当我尝试使用 objectAtIndex 访问对象时崩溃了,因为索引超出范围(该索引处的对象已从另一个线程的数组中删除) )。我在网上搜索了如何解决这个问题,我决定尝试这个解决方案。我用<$做了一个课c $ c> NSMutableArray 属性,请参阅以下代码:

In my app I'm accessing and changing a mutable array from multiple threads. At the beginning it was crashing when I was trying to access an object with objectAtIndex, because index was out of bounds (object at that index has already been removed from array in another thread). I searched on the internet how to solve this problem, and I decided to try this solution .I made a class with NSMutableArray property, see the following code:

@interface SynchronizedArray()
@property (retain, atomic) NSMutableArray *array;
@end

@implementation SynchronizedArray

- (id)init
{
    self = [super init];
    if (self)
    {
        _array = [[NSMutableArray alloc] init];
    }
    return self;
}

-(id)objectAtIndex:(NSUInteger)index
{
    @synchronized(_array)
    {
        return [_array objectAtIndex:index];
    }
}

-(void)removeObject:(id)object
{
    @synchronized(_array)
    {
        [_array removeObject:object];
    }
}

-(void)removeObjectAtIndex:(NSUInteger)index
{
    @synchronized(_array)
    {
        [_array removeObjectAtIndex:index];
    }
}

-(void)addObject:(id)object
{
    @synchronized(_array)
    {
        [_array addObject:object];
    }
}

- (NSUInteger)count
{
    @synchronized(_array)
    {
        return [_array count];
    }
}

-(void)removeAllObjects
{
    @synchronized(_array)
    {
        [_array removeAllObjects];
    }
}

-(id)copy
{
    @synchronized(_array)
    {
        return [_array copy];
    }
}

我使用这个类而不是旧的可变数组,但该应用程序仍然崩溃在这一行: return [_array objectAtIndex:index]; 我还尝试了这种方法 NSLock ,但没有运气。我做错了什么以及如何解决这个问题?

and I use this class instead of old mutable array, but the app is still crashing at this line: return [_array objectAtIndex:index]; I tried also this approach with NSLock, but without a luck. What I'm doing wrong and how to fix this?

推荐答案

我认为这个解决方案很糟糕。考虑一下:

I believe this solution is poor. Consider this:


  1. 线程#1调用 count 并被告知有4个对象在数组中。

  2. 数组未同步。

  3. 线程#2调用 removeObjectAtIndex:2 在数组上。

  4. 数组未同步。

  5. 线程#1调用 objectAtIndex:3 发生错误。

  1. thread #1 calls count and is told there are 4 objects in the array.
  2. array is unsynchronized.
  3. thread #2 calls removeObjectAtIndex:2 on the array.
  4. array is unsynchronized.
  5. thread #1 calls objectAtIndex:3 and the error occurs.

相反,您需要一个更高级别的锁定机制,其中锁定在步骤1和5和线程#2无法在这些步骤之间删除对象。

Instead you need a locking mechanism at a higher level where the lock is around the array at both steps 1 and 5 and thread #2 cannot remove an object in between these steps.

这篇关于NSMutableArray线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆