objective c - How to know when a job that require multiple threading has finished? -
one thing is:
-(void)grabbingprocess:(void (^)())block; { self.othergrabbingindicator +=1; block(); dispatch_after(dispatch_time(dispatch_time_now, 2 * nsec_per_sec), dispatch_get_current_queue(), ^{ self.othergrabbingindicator -=1; }); } everytime want run may take long time in background,
[grabclass grab] grabbingprocess: ^{ //do grab data etc. }];
there many such functions , many such data. example, @ first grab businesses id. grab details on businesses on separate thread.
i want know time when threads have finished , post suitable notification.
the problem solution after while, quite value of self.othergrabbingindicator hover around 2 or 3 never going down though of thread have finished.
somehow of self.othergrabbingindicator +=1; "leaked" , not matched self.othergrabbingindicator -=1. wonder how can leak ever happen?
if want run blocks asynchronously , find out when they're done, appropriate tool dispatch_group. can dispatch blocks onto specific group , queue using dispatch_group_async(), , group track when block finished. can either wait synchronously on group finish dispatch_group_wait() or register block invoked when group done dispatch_group_notify().
the reason why solution above doesn't work because aren't accessing/mutating counter in threadsafe way. here's trivial series of events cause problem:
start: self.othergrabbingindicator 1
thread a: reads self.othergrabbingindicator
thread b: reads self.othergrabbingindicator
thread a: increments read value , writes self.othergrabbingindicator
thread b: increments read value , writes self.othergrabbingindicator
end: self.othergrabbingindicator 2
even though 2 threads tried increment it, 1 "succeeded" , end losing other increment. can happen during decrement. if use dispatch groups problem goes away.
as side note, should never use dispatch_get_current_queue(). debugging function never supposed used in actual code. primary reason because aren't running on 1 queue, you're running on whole hierarchy of queues simultaneously, function can tell 1 queue. in addition, may running on someone's private queue , should not dispatching onto yourself.
Comments
Post a Comment