multithreading - Design pattern for asynchronous while loop -


i have function boils down to:

while(dowork) {   config = generateconfigurationfortesting();   result = executework(config);   dowork = isdone(result); } 

how can rewrite efficient asynchronous execution, assuming functions thread safe, independent of previous iterations, , require more iterations maximum number of allowable threads ?

the problem here don't know how many iterations required in advance can't make dispatch_group or use dispatch_apply.

this first attempt, looks bit ugly me because of arbitrarily chosen values , sleeping;

int thread_count = 0; bool dowork = true; int max_threads = 20;  // arbitrarily chosen number  dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0);  while(dowork) {   if(thread_count < max_threads)   {     dispatch_async(queue, ^{ config myconfig = generateconfigurationfortesting();                              result myresult = executework();                              dispatch_async(queue, checkresult(myresult)); });     thread_count++;   }   else     usleep(100); // don't consume cpu }  void checkresult(result value) {   if(value == good) dowork = false;   thread_count--; } 

based on description, looks generateconfigurationfortesting kind of randomization technique or otherwise generator can make near-infinite number of configuration (hence comment don't know ahead of time how many iterations need). assumption, stuck model you've created, since executor needs limited reasonable assumptions queue , don't want over-generate, extend length of run after have succeeded in finding value ==good measurements.

i suggest consider using queue (or osatomicincrement* , osatomicdecrement*) protect access thread_count , dowork. stands, thread_count increment , decrement happen in 2 different queues (main_queue main thread , default queue background task) , simultaneously increment , decrement thread count. lead undercount (which cause more threads created expect) or overcount (which cause never complete task).

another option making little nicer have checkresult add new elements queue if value!=good. way, load initial elements of queue using dispatch_apply( 20, queue, ^{ ... }) , don't need thread_count @ all. first 20 added using dispatch_apply (or amount dispatch_apply feels appropriate configuration) , each time checkresult called can either set dowork=false or add operation queue.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -