我的软件中有两个功能会导致重要的延迟问题。该软件是用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;
}
你有什么想法或建议吗?