我的软件中有两个功能会导致严重的延迟问题。该软件是用 Objective-C 编写的。我从 USB 设备接收串行数据,我的目标是封装它们,然后将它们发送到另一个将处理数据的对象。
这部分程序会导致大量的CPU和延迟问题,我根本不知道如何解决这个问题。设备仅在其状态发生变化时才发送数据,因此当发生大量变化时,一切都会变得迟缓..
- (void)getSerialData {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[self getSerialDataLoop];
});
}
- (void)getSerialDataLoop {
readThreadRunning = YES;
char byte_buffer[2]; // buffer for holding incoming data
int numBytes=0; // number of bytes read during read
NSString *text;
// this will loop untilthe serial port closes
while(TRUE) {
// read() blocks until some data is available or the port is closed
numBytes = (int)read(serialFileDescriptor, byte_buffer, 1); // read up to the size of the buffer
if(numBytes>0) {
///text = [NSString stringWithCString:byte_buffer encoding:NSSymbolStringEncoding];
if(![text isEqualToString:@""]){
text = [NSString stringWithUTF8String:byte_buffer];
[self performSelectorOnMainThread:@selector(processNSStringData:) withObject:text waitUntilDone:YES];
}
} else {
break; // Stop the thread if there is an error
}
}
// make sure the serial port is closed
if (serialFileDescriptor != -1) {
close(serialFileDescriptor);
serialFileDescriptor = -1;
}
// mark that the thread has quit
readThreadRunning = FALSE;
}
您有什么想法或建议吗?
最佳答案
您基本上已经在这里重新发明了 NSStream
。我首先建议您研究这个与运行循环相关的现有解决方案。
您还可能很容易因调用 getSerialData
而不知所措。系统中没有任何东西可以阻止对此例程的多次调用,如果您进行多次调用,您将遇到并发操作。使用 NSStream 可以解决这个问题。但无论如何,如果一个读 block 已经在运行,您就不应该继续创建新的读 block 。
您还一次读取一个字节并对其进行处理。这可能是您最大的影响。为每个字节回调主线程可能非常昂贵。如果不出意外,您将为每个字节创建一个新的 NSString
对象。
请注意,您的代码非常危险,可能会崩溃。您从未初始化byte_buffer
,并且只读取一个字节到其中。当您调用 stringWithUTF8String:
时,您假设第二个字节是\0,这取决于堆栈的当前状态。
关于objective-c - 读取串行数据时 CPU 消耗和延迟较高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059726/