Motti Shneor
Motti Shneor

Reputation: 2194

Is NSOutputStream thread safe for the close and writeData methods?

My program frequently crashes (bad access) on the following line:

int writeSize = [_outputStream write:pCopyOfDataBuff maxLength:sendLength];

pCopyOfDataBuff is a

pCopyOfDataBuff = new unsigned char [sendLength];

allocated and filled with data on the stack just before the crashing line. Context is a special thread handling this stream.

When I stop in the debugger, using symbolic exception breakpoint, I find that the _outputStream was actually closed.

[_outputStream close];

was closed in the MAIN thread. Now this may have happened concurrently.

My question: Is it at all safe to handle an NSOutputStream like this, in multiple threads? Should I synchronize ALL calls to an NSStream to the same thread?

Thanks. I can't find simple answer in the docs.

Upvotes: 0

Views: 1225

Answers (1)

Delblanco
Delblanco

Reputation: 681

Recently encountered the same problem. I discovered that some delegate on the main thread shuts down the operation queue with [myQueue cancelAllOperations] and closes the connection as followed:

-(void)closeStream:(NSStream *)stream {
    [stream setDelegate:nil];
    [stream close];
    [stream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

My explanation was that in the middle of writing with [self.outputStream write:bytes maxLength:bytesRecieved]; the output stream was closed.

I resolved it by waiting on the NSOperationQueue to finish: [myQueue waitUntilAllOperationsAreFinished].

Hopes this helps to resolve your issue.

Upvotes: 3

Related Questions