Hi.
I have an NSOutputStream created and scheduled on some pre-created NSTrhead’s NSRunloop (a.k.a mySocketThread).
Now I wish to write to that stream in NSOperations that are scheduled on a serial NSOperationQueue (only one operation at a time). Important point is, I never know in what thread/context my SendMessageOperation will run.
When it runs (main called by operation’s start) I inquire the stream for hasSpaceAvailable, and if so, I attempt to write my message. Otherwise, I set the operation object as delegate to the outputStream and bail - waiting for NSStreamEventHasSpaceAvailable. I do the same if I fail to write the complete message (only some of it written).
Now the stream is scheduled on another thread’s runloop - which says I may receive stream events concurrently to my operation’s running. Synchronizing inside an NSOperation is plain ugly, and a bit against the reason I’m working with operation queues on the first place...
I have special difficulty with operation cancellation. I can (of course) cancel scheduled messages that didn’t start, but I cannot (server protocol) send half-messages to my server - hence I can only abort a cancelled operation if stream error or end occurred (again - I can only know this via stream events).
My question is this:
If I (upon starting my operation) schedule the outputStream on the current operation’s runloop like thus:
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
Will it automatically be removed from the original runloop it was scheduled on? (mySocketThread’s runloop)?
Is re-scheduling the stream frequently advisable? If I change it from one runloop to another, are there any “gaps” in which I can lose important events (that will be handled by the output stream internally without me knowing) ?
If I can change the outputStream’s scheduling to use the same of my currently running operation - that should solve my synchronizing problem. My operation can bail safely, and be re-called on its own thread, without concurrency.
Any hint will be greatly appreciated.
Thanks. |