copying data over in objective C from ring buffer in a thread safe manner

半城伤御伤魂 提交于 2019-12-24 07:45:14

问题


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
 }

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
}

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?


回答1:


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



来源:https://stackoverflow.com/questions/12653284/copying-data-over-in-objective-c-from-ring-buffer-in-a-thread-safe-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!