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):
在另一个线程中,我正在读取它(并将数据复制到NSData变量):
-(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?
虽然我通过[NSData:dataWithBytes:length]将值复制到ringBufferReadData,并将ringBufferReadData声明为@property(非原子,复制)NSData * ringBufferReadData; ..我假设我的ringBufferReadData本地副本与环形缓冲区无关因此,我不必担心读取的线程顺序和线程缓冲区的权限。但是..事实证明,在将数据复制到ringBufferReadData之后,它的值会被写入环形缓冲区的其他线程更改。任何想法如何/为什么以及如何确保不会发生这种情况?
1 个解决方案
#1
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
原来问题是代码中的其他地方.. [NSData dataWithBytes:length]确实创建了一个新的NSData对象,如Martin R所述
#1
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
原来问题是代码中的其他地方.. [NSData dataWithBytes:length]确实创建了一个新的NSData对象,如Martin R所述