Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top