我对这段代码的结果感到困惑:
在一个线程中,我正在写入环形缓冲区(请参阅环形缓冲区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变量):
-(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并将ringBufferReadData声明为@property (nonatomic, copy) NSData *ringBufferReadData;
..我假设我的ringBufferReadData本地副本与环形缓冲区无关,因此我不知道t不得不担心读取的线程顺序和线程缓冲区的权限..然而..事实证明,在将数据复制到ringBufferReadData之后,它的值会被另一个线程写入环形缓冲区而改变..任何想法如何/为什么以及如何确保不会发生这种情况?
答案 0 :(得分:1)
事实证明问题出在代码中的其他地方.. [NSData dataWithBytes:length]确实创建了一个新的NSData对象,如Martin R所述