我的軟件中有兩個功能會導致重要的延遲問題。該軟件是用Objective-C編寫的。我從USB設備接收串行數據,我的目標是封裝它們,然後將它們發送到另一個處理數據的對象。讀取串行數據時CPU消耗和延遲較高
該部分的程序會導致大cpu和延遲問題,我不知道如何解決這個問題。該裝置只有當它的狀態變化,因此當很多的變化以及發生的一切都變得laggy發送數據..
- (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;
}
你有任何意見或指針?