Does the dispatch_after method execute simultaneously in this code?

int total = 0; // these are globals.. BOOL dispatchCalled = NO; // -(void) callDispatch { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{ dispatchCalled = YES; NSLog(@"Total, after 300ms, is %i", total); }); } -(void)play // this is my "main" method.. { NSLog(@"app starts running"); [self callDispatch]; while(!dispatchCalled) { total++; } [self callDispatch]; } 
Console

:

  2012-08-02 20:36:05.357 MyProject[8245:1a07] app starts running 2012-08-02 20:36:05.693 MyProject[8245:3d03] Total, after 300ms, is 11513522 2012-08-02 20:36:05.993 MyProject[8245:3d03] Total, after 300ms, is 11513523 

When the method enclosed in callDispatch is executed for the first time, the while-loop managed to execute 11513522 times. At this point, the while-loop condition is set to YES , and the while loop should run no more. However, it runs again before it confirms the update by the condition of the submit method. Why is this?

This is because the method enclosed in callDispatch will execute in parallel / in parallel with the while loop, which explains why the confirmation of another loop is needed for the while loop?

+4
source share
2 answers

Yes, it starts at the same time. This means that your block can be executed at any time during the while loop, for example, after passing a condition, but before it increases global or after increasing global. If you run your code several times, you will notice that sometimes the number of total matches matches, and sometimes not. (Edit: this means your code is "non-deterministic" when run at the same time.)

If you try to run your code in a sequential queue, the while loop will run indefinitely and no resulting values ​​will be printed. In the sequential queue, the block that you plan in callDispatch is added to the queue that will be called next, but provided that the infinite loop never quits, nothing in this queue will ever be called.

More info at Apple Doc: GCD offers three different types of queues

+1
source

Given that you effectively block the main event loop, then the queue in which the blocks are executed should not be the main queue.

Therefore, you definitely have two threads, and thus there is no real guarantee of how much time can elapse between the first block and the second executable block. Also, if dispatch_get_current_queue () happens to get an asynchronous queue, you may not understand anything about the simultaneous execution of any blocks in it.

Or, speaking more frankly: you cannot talk about execution and planning patterns in parallel code; you cannot “play on the computer” and invent anything other than approximating what happened in one situation.

0
source

All Articles