objective c - Limiting number of threads -


i need download images through background threads, limit number of threads. maximum thread number must 5 , in each thread must 1 serial queue. client-server using socket rocket library. main trouble don't need nsoperation pluses canceling operations. looking simple decision, can found this:

self.limitingsema = dispatch_semaphore_create(koperationlimit);     dispatch_queue_t concurentqueue = dispatch_queue_create("limiting queue", dispatch_queue_concurrent);     dispatch_async(concurentqueue, ^{         dispatch_semaphore_wait(self.limitingsema, dispatch_time_forever);          /* upload image here */          dispatch_semaphore_signal(self.limitingsema);     }); 

but how limit number of threads , wait new operations starting, until not ready in queue ?

is control number of queues ?

nsarray *queues = @[dispatch_queue_create("com.you.binaryqueue_1", dispatch_queue_serial),                     dispatch_queue_create("com.you.binaryqueue_2", dispatch_queue_serial),                     dispatch_queue_create("com.you.binaryqueue_3", dispatch_queue_serial)                     ];  nsuinteger randqueue = arc4random() % [queues count]; dispatch_async([queues objectatindex:randqueue], ^{     nslog(@"do something"); }); randqueue = arc4random() % [queues count]; dispatch_async([queues objectatindex:randqueue], ^{     nslog(@"do else"); }); 

gcd has no option limit amount of concurrent blocks running.

this potentially create 1 thread waits each operation enqueue. gcd dynamically adjusts number of threads uses. if enqueue block , gcd has no more threads available spin thread if notices there free cpu cores available. since worker thread sleeping inside block cpu considered free. cause many threads using lot of memory - each thread gets 512 kb of stack.

your best option use nsoperationqueue can control directly how many operations run in parallel using maxconcurrentoperationcount property. easier (less code write, test , debug) , more efficient.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -