How to throttle rate of NSInputStream?
How to throttle rate of NSInputStream?
- Subject: How to throttle rate of NSInputStream?
- From: Jens Alfke <email@hidden>
- Date: Mon, 26 Mar 2012 16:13:41 -0700
[I posted this to macnetworkprog earlier today, but 3 hours later it hasn’t shown up yet, so I’m trying here too.]
I’m using an async NSInputStream to read from a TCP socket. Given a good connection, the data comes in faster than an iOS device can parse it (it’s a stream of small JSON docs, one per line.) I’m performance-tuning my code, and finding that NSInputStream is shoving all of the data down my throat at once, without giving the runloop a chance to process any other input sources. This means that my thread is blocked, and other tasks scheduled on it don’t get a chance to run, until I’ve read the whole feed, which takes over a minute. (And there’s also the fact that CFNetwork must be buffering megabytes of data from the socket that my code hasn’t read yet.)
This seems to hinge on the way the stream calls my event handler. When I get the NSStreamEventHasBytesAvailable, I only read 8k bytes of data at a time, then return. What seems to happen is that, if that didn’t consume all of the available data, the stream will keep sending me the event in a tight loop without exiting back to the runloop in between.
What can I do about this? Ideally I’d like the stream to hold off on reading more from the socket until my code finishes processing the buffer. As a second choice, I’d like it to at least return the runloop more often so my other tasks get time to run.
—Jens
_______________________________________________
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