I am using dispatch_semaphore_wait to stop my current thread but it looks like it stops all my threads.
Code:
SampleReader *reader = [[SampleReader alloc] initWithHostname:hostname andFilePath:filepath];
reader.endHandler = endHandler;
[reader start];
dispatch_semaphore_wait(reader->mSem, DISPATCH_TIME_FOREVER);
My start method has something like:
mFileStream = [[NSOutputStream outputStreamToFileAtPath:[fileurl path] append:FALSE] retain];
[mFileStream open];
mNetworkStream = (NSInputStream *)CFReadStreamCreateWithFTPURL(NULL, (CFURLRef)ftpurl);
mNetworkStream.delegate = self;
[mNetworkStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[mNetworkStream open];
I get callback in one of the delegate methods wherein I signal the semaphore
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
switch (eventCode)
Case NSStreamEventErrorOccurred:
dispatch_semaphore_signal(mSem);
break;
case NSStreamEventEndEncountered:
dispatch_semaphore_signal(mSem);
break;
}
However, when i send wait on semaphore, the delegate method is not called.
Its called only when i comment out the line
//dispatch_semaphore_signal(mSem);
Any help will be greatly appreciated.
If you’re calling
[reader start]from your main thread then you are creating a deadlock. Your stream is being associated with the main thread here:That means for it to work the main run loop must be spinning. If the
dispatch_semaphore_waitis on the main thread though, you’re stopping the run loop and preventing the stream from handling its events.I don’t see how commenting out the
dispatch_semaphore_signalwould do anything besides make thewaitnever return.