Re: How to throttle rate of NSInputStream?
Re: How to throttle rate of NSInputStream?
- Subject: Re: How to throttle rate of NSInputStream?
- From: Dave Keck <email@hidden>
- Date: Tue, 27 Mar 2012 02:35:15 -0400
> [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];
Running the runloop recursively in the default mode is almost always a
bad idea; doing so triggers callouts that parent stack frames almost
certainly weren't designed to handle when they occur from within the
method you're writing. It's very much analogous to the issues that
arise in multithreading: just as threaded code must ensure critical
sections are executed atomically, other code must ensure that within
certain critical sections, timers won't fire, notifications won't be
posted, and run loop sources and observers won't be handled.
A concrete example: legacy versions of IOBluetoothDevice used to run
the run loop (in the default mode) within its -isConnected getter,
with the idea that it would refresh its connected flag with the most
up-to-date state before returning it. The result is that when client
code calls -isConnected, timers are fired, distributed notifications
are posted, etc., all within -isConnected! There are a million ways
this could wreak havoc, but suppose we have this code:
- (void)doSomething
{
_timeoutTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 ...
selector: @selector(cleanup)];
if (![bluetoothDevice isConnected])
[self cleanup];
}
- (void)cleanup
{
[_timeoutTimer invalidate];
}
Suppose two things: -isConnected takes long enough that _timeoutTimer
fires within its stack frame, and -isConnected returns NO. In this
case, the -cleanup method is called twice (once from within
-isConnected, and once from within -doSomething), which is clearly
unexpected behavior. Perhaps this example seems unrealistic, but in
any code that makes serious use of timers, distributed notifications,
run loop sources or run loop observes, the assumption that the run
loop won't be run recursively in the default mode is everywhere.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden