1

I am porting an app reading data from a BT device to Mac. On the mac-specific code, I have a class with the delegate methods for the BT callbacks, like -(void) rfcommChannelData:(...)

On that callback, I fill a buffer with the received data. I have a function called from the app:

-(int) m_timedRead:(unsigned char*)buffer length:(unsigned long)numBytes time:(unsigned int)timeout
{

double steps=0.01;
double time = (double)timeout/1000;
bool ready = false;
int read,total=0;
unsigned long restBytes = numBytes;
while(!ready){
    unsigned char *ptr = buffer+total;
    read = [self m_readRFCOMM:(unsigned char*)ptr length:(unsigned long)restBytes];
    total+=read;
    if(total>=numBytes){
        ready=true; continue;
    }
    restBytes = numBytes-total;
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, .4, false);       
    time -= steps;
    if(time<=0){
        ready=true; continue;
    }
}

My problem is that this RunLoop makes the whole app un extremely slow. If I don't use default mode, and create my on runloop with a runlooptimer, the callback method rfcommChannelData never gets called. I create my one runloop with the following code:

//  CFStringRef myCustomMode = CFSTR("MyCustomMode");
//  CFRunLoopTimerRef myTimer;
//  myTimer = CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+1.0,1.0,0,0,foo,NULL);   
//  CFRunLoopAddTimer(CFRunLoopGetCurrent(), myTimer, myCustomMode);
//  CFRunLoopTimerInvalidate(myTimer);
//  CFRelease(myTimer);

Any idea why the default RunLoop slows down the whole app, or how to make my own run loop allow callbacks from rfcommchannel being triggered?

Many thanks,

Anton Albajes-Eizagirre

antonae
  • 11
  • 3

1 Answers1

1

If you're working on the main thread of a GUI app, don't run the run loop internally to your own methods. Install run loop sources (or allow asynchronous APIs of the frameworks install sources on your behalf) and just return to the main event loop. That is, let flow of execution return out of your code and back to your caller. The main event loop runs the run loop of the main thread and, when sources are ready, their callbacks will fire which will probably call your methods.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154