Each NSThread
can inherently provide an NSRunLoop
, so there's nothing to write there. All you really need be concerned with is pumping the NSRunLoop periodically (assuming you haven't attached any of the objects, such as NSTimer
, that implicitly do this for you).
So e.g.
// create a thread and point it to an agent that
// knows how to pump the run loop
myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(startRunLoop)
object:nil];
// start the thread
[serialDispatchThread start];
/* ... elsewhere ... */
- (void)startRunLoop
{
// consider setting a thread name here, as it'll help with debugging
// I'm lazily using a volatile bool for my quit flag; do whatever you
// think is appropriate
while(!quitThread)
{
// run the runloop for another 2 seconds,
// wrapping it in an autorelease pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSRunLoop currentRunLoop] runUntilDate:
[NSDate dateWithTimeIntervalSinceNow:2.0]];
[pool drain];
}
}
/* puts you in a position to be able, whenever you want to issue things like: */
[self
performSelector:@selector(myAsynchronousAction)
onThread:myThread
withObject:nil
waitUntilDone:NO];
So what you've done there is set yourself up with something a lot like a GCD serial dispatch queue.