2012-10-25 40 views
2

我的軟件中有兩個功能會導致重要的延遲問題。該軟件是用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; 
} 

你有任何意見或指針?

回答

1

你基本上在這裏重新創造了NSStream。我首先建議您調查這個已經可用的解決方案,它與運行循環相關聯。

你也可以很容易地打電話給getSerialData。系統中的任何內容都不會阻止對該例程的多次調用,並且如果您進行多次調用,則會發生併發操作。使用NSStream可以解決這個問題。但是,無論如何,如果已經在運行,您不應該繼續創建新的讀取塊。

您還在讀取一個字節並處理它。這可能是你最大的影響。回調每個字節的主線程可能相當昂貴。如果沒有其他內容,則爲每個字節創建一個新的NSString對象。

請注意,您的代碼非常危險,可能會崩潰。你永遠不會初始化byte_buffer,你只能讀入一個字節。當你打電話給stringWithUTF8String:時,你假定第二個字節是\ 0,這取決於堆棧的當前狀態。