以线程安全的方式从环形缓冲区复制目标 C 中的数据 [英] copying data over in objective C from ring buffer in a thread safe manner

查看:128
本文介绍了以线程安全的方式从环形缓冲区复制目标 C 中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这段代码的结果感到困惑:

I'm puzzled over the result of this code:

在一个线程中,我正在写入环形缓冲区(请参阅环形缓冲区的实现 此处):

In one thread I'm writing to the ring buffer (see implementation of ring buffer here):

- (void)appendToRingBuffer:(Packet *)packet
{
    int32_t length = ((PacketAudioBuffer *)packet).totalSize;

    void *writePointer;
    bytesAvailableToWrite = [ringBuffer lengthAvailableToWriteReturningPointer:&writePointer];
    memcpy(writePointer, [((PacketAudioBuffer *)packet).audioBufferData bytes], length);
    [ringBuffer didWriteLength:length];   //updates ring buffer head pointer
 }

在另一个线程中,我正在读取它(并将数据复制到 NSData 变量中):

And in another thread, i'm reading from it (and copying the data unto an NSData variable):

-(BOOL)readFromRingBuffer
{ 
    void *readPointer;
    allBytesAvailable = [ringBuffer lengthAvailableToReadReturningPointer:&readPointer];

    ringBufferReadData = [NSData dataWithBytes:readPointer length:allBytesAvailable];
    [ringBuffer didReadLength:allBytesAvailable];    // purges read data from ring buffer

    // do something with ringBufferReadData
}

尽管我通过 [NSData:dataWithBytes:length] 并通过将 ringBufferReadData 声明为 @property (nonatomic, copy) NSData *ringBufferReadData; 将值复制到 ringBufferReadData.. 我假设我的 ringBufferReadData 本地副本与环形缓冲区无关,因此我不必担心读取的线程顺序和线程缓冲区的权限......但是......结果证明在复制之后数据到 ringBufferReadData,它的值因另一个线程写入环形缓冲区而改变.. 知道如何/为什么以及如何确保这不会发生吗?

although I copied the values over to ringBufferReadData via [NSData:dataWithBytes:length] and by declaring ringBufferReadData as @property (nonatomic, copy) NSData *ringBufferReadData;.. I assumed that my local copy of ringBufferReadData has nothing to do with the ring buffer, hence I don't have to worry about the thread order of reads and rights to the thread buffer.. however.. it turns out that after copying the data to ringBufferReadData, it's value changes by the other thread writing to the ring buffer.. any idea how/why and how to ensure that this doesn't happen?

推荐答案

事实证明问题出在代码的其他地方.. [NSData dataWithBytes:length] 确实创建了一个新的 NSData 对象,正如 Martin R 提到的

it turns out that the problem was somewhere else in the code.. [NSData dataWithBytes:length] does create a new NSData object as mentioned by Martin R

这篇关于以线程安全的方式从环形缓冲区复制目标 C 中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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