【问题标题】:Synchronizing NSMutableData troubles同步 NSMutableData 的麻烦
【发布时间】:2011-09-21 13:27:28
【问题描述】:

我们有一个 NSMutableData 对象,它经常附加数据。我们也经常通过bytes方法拉取数据进行读取。

我们已经通过 pthread 互斥锁同步了对这个 NSMutableData 对象的访问:

pthread_mutex_t _mutex;

pthread_mutexattr_t attributes;
pthread_mutexattr_settype( &attributes, PTHREAD_MUTEX_DEFAULT );
pthread_mutex_init( &_mutex, &attributes );

然后每次我们访问这个对象时:

pthread_mutex_lock(&_mutex);
const UInt8* rawData = [_coverage bytes];
//code that works with the raw bytes
pthread_mutex_unlock(&_mutex);

此外,每个addData 方法在向 NSMutableData 对象添加数据之前都会锁定互斥锁。

问题是我们在使用rawData 时仍然偶尔会收到EXC_BAD_ACCESS。我知道 NSMutableBytes 会随着数据的添加而增加其字节数组。我也明白我不应该期望rawData 也会神奇地成长。

我只是想知道,当我们明确锁定读写访问权限时,我们怎么会遇到rawData 从我们下面释放出来的情况?

我们是否对互斥体或访问字节的方式做错了什么?

编辑

我发现了获得 EXC_BAD_ACCESS 的真正原因。我没有初始化互斥体属性,所以锁定互斥体什么也没做。这是更正后的代码:

pthread_mutex_t _mutex;

pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutex_init(&_mutex, &attributes);
pthread_mutexattr_destroy(&attributes);

【问题讨论】:

    标签: objective-c core-foundation


    【解决方案1】:

    是的,它有可能从你的身下被释放出来。

    根据documentation

    字节
    返回一个指向接收者内容的指针。

    您应该制作数据的副本,以确保它不会被更改或从您的下方释放。完成副本后,请务必free()

    pthread_mutex_lock(&_mutex);
    const UInt8 *origData = [_coverage bytes];
    UInt8 *rawData;
    memmove(rawData, origData, [_coverage length]);
    
    //code that works with the raw bytes
    free(rawData);
    pthread_mutex_unlock(&_mutex);
    

    【讨论】:

    • 是每次都通过公共api访问字节更好,还是只管理我们自己的字节数组更好?
    • 这真的取决于它的使用方式,因为 NSMutableData 使得附加数据变得更加容易。正如你所说,互斥锁本身不能工作似乎很奇怪,但是如果在那个确切的互斥锁之外的某个地方改变了可能是问题的数据。您没有发布附加操作,请仔细检查并确保它正确锁定。
    猜你喜欢
    • 2015-12-31
    • 2013-01-18
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 2011-06-12
    相关资源
    最近更新 更多