Quantcast
Channel: semaphore not waiting for second time function call for web service in ios - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Rob for semaphore not waiting for second time function call for web service in ios

$
0
0

Your first example does not perform dispatch_semaphore_wait on the last iteration of the loop, but rather it curiously issues yet another dispatch_semaphore_signal. Assuming your delegate always issues a signal, you'll end up with a mismatch of semaphore signals.

As a result, if you use the same semaphore in the second example, you'll likely end up with two extra signals (not only the signal you issued in your for loop in your first example when index was count - 1, but presumably your last iteration of the delegate method also likely issued an unsatisfied signal), and thus three requests in your second loop will run concurrently.

When you use this semaphore pattern, make sure each "signal" is matched by a "wait". If you add print statements at each "signal" and "wait", these sorts of unbalanced calls will jump out at you (rather than seeing alternating "wait" and "signal" calls, you'll see a series of "signal" calls in succession (in this case, at the end of the first for loop)).

Bottom line, you likely want to remove the if index == count-1 { ... } check, and just dispatch_semaphore_wait. If there's something weird going on in the delegate methods that requires some logic here, you should edit your question showing us why you employed the logic you did.

Even better, you really should excise your code of these semaphores altogether, and instead embrace asynchronous patterns. Writing synchronous code feels so intuitive, but it actually is inefficient (blocking threads; losing huge benefit of concurrent requests; etc.) and problematic (susceptible to deadlocking; should never be done from main thread; etc.). You should embrace asynchronous patterns such as dispatch groups or NSOperation dependencies.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>