objective c - iOS: Don't return from function until multiple background threads complete -
this seems should simple i'm having lot of trouble. have function fires off bunch of other functions run in background , have completion blocks. want function wait until of completion blocks have been called before returns.
i not have control of function calling executes in background. otherwise modify use dispatch_async own queue , wait on queue finish.
example of situation looks like:
- (void)functionthatshouldbesynchronous { (int = 0; < 10; i++) { [self dosomethinginbackground:^{ nslog(@"completed!"); }]; } // how wait until 10 threads have completed before returning? } - (void)dosomethinginbackground:(void(^)())completion { dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_background, 0), ^{ [nsthread sleepfortimeinterval:1.0f]; // stuff completion(); // execute completion block }); }
thanks in advance.
use dispatch group this:
- (void)functionthatshouldbesynchronous { dispatch_group_t taskgroup = dispatch_group_create(); (int = 0; < 10; i++) { dispatch_group_enter(taskgroup); [self dosomethinginbackground:^{ nslog(@"completed!"); dispatch_group_leave(taskgroup); }]; } // waiting threads dispatch_group_wait(taskgroup, dispatch_time_forever); dispatch_release(taskgroup); // background work complete }
if want timeout waiting threads change dispatch_group_wait line this
// waiting 10 seconds before giving if (dispatch_group_wait(taskgroup, dispatch_time(dispatch_time_now, 10000000000)) != 0) { // timeout }
the parameter in nanoseconds.
as bbum saying, shouldn't block main thread. in case this:
typedef void(^mycompletionhandler)(); -(void)functiondoingbackgroundworkwithcompletionhandler:(mycompletionhandler)completionhandler { dispatch_group_t taskgroup = dispatch_group_create(); (int = 0; < 10; i++) { dispatch_group_enter(taskgroup); [self dosomethinginbackground:^{ nslog(@"completed!"); dispatch_group_leave(taskgroup); }]; } dispatch_queue_t waitingqueue = dispatch_queue_create("com.mycompany.myapp.waitingqueue", dispatch_queue_concurrent); dispatch_async(waitingqueue, ^{ // waiting threads dispatch_group_wait(taskgroup, dispatch_time_forever); dispatch_release(taskgroup); // background work complete dispatch_async(dispatch_get_main_queue(), ^{ // calling completion handler on main thread (if like) completionhandler(); }); dispatch_release(waitingqueue); }); }
Comments
Post a Comment