Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I limit concurrent requests using GCD?

I'm acquiring data from a database asynchronously. Is there any way I can limit the concurrent requests to a number, but still execute the rest?

I saw a post using NSOperation and NSOperationQueue but this is too complicated for me. Is there any other ways to do it? Can GCD achieve it?

like image 516
user1491987 Avatar asked Jan 18 '13 07:01

user1491987


1 Answers

Something like this:

...
//only make one of these obviously :) remaking it each time you dispatch_async wouldn't limit anything
dispatch_semaphore_t concurrencyLimitingSemaphore = dispatch_semaphore_create(limit);
...
//do this part once per task, for example in a loop
dispatch_semaphore_wait(concurrencyLimitingSemaphore, DISPATCH_TIME_FOREVER);
dispatch_async(someConcurrentQueue, ^{
    /* work goes here */
    dispatch_semaphore_signal(concurrencyLimitingSemaphore);
}
like image 138
Catfish_Man Avatar answered Sep 23 '22 01:09

Catfish_Man