iosmultithreadingrunloop

InputStream ios works without a RunLoop


I am writing an iOS app using InputStream and OutputStream. However, I find that I can both read and write from the streams without scheduling them in a RunLoop!

I here is my ThreadFunc. Notice that I have commented out all the runLoop code, but it still works!

@objc func threadFunc(){
    var dataToSend: Data?;

    print("Inside threadFunc loop!");

    //self.m_ReadStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.commonModes );
    self.m_ReadStream!.open();

    //self.m_WriteStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.commonModes );
    self.m_WriteStream!.open()

    var once = false;

    while( !m_Calcelled ){
        let wStat = self.m_WriteStream?.streamStatus;
        let rStat = self.m_ReadStream?.streamStatus;

        if( dataToSend == nil && self.m_Lock.lock(before: Date(timeIntervalSinceNow: 10 ) )){
            dataToSend = self.m_DataToSend; // Make local copy
            self.m_DataToSend = nil;
            self.m_Lock.unlock();
        }

        if( dataToSend != nil && wStat == .open ){
            let totalBytesSent = self.sendDataBlock( d:dataToSend! );
            if( totalBytesSent == dataToSend?.count ){
                print("successfully sent the packet.");
            }
        }
        //let untilDate: Date = Date(timeIntervalSinceNow: 5 );
        //print("SocketThread. Calling runLoop...");
        //RunLoop.current.run( mode: .defaultRunLoopMode, before: untilDate );
        //print("SocketThread is waiting for action....");
        //sleep(1);   // Sleep for 1 second...
    }
}

Solution

  • As the docs note:

    Unless the client is polling the stream, it is responsible for ensuring that the stream is scheduled on at least one run loop and that at least one of the run loops on which the stream is scheduled is being run.

    You're polling the stream. This isn't generally how streams are meant to be used, but since you are, it doesn't require a runloop.