Reputation: 1576
In the following sample function
-(void)testThred{
dispatch_queue_t serialQueue = dispatch_queue_create("com.unique.name.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(serialQueue, ^{
NSLog(@"1");
});
NSLog(@"2");
dispatch_async(serialQueue, ^{
NSLog(@"3");
});
NSLog(@"4");
}
the output is as follows 2,1,4,3
as per my knowledge it will be 2, 4 ,1,3 anyone know how
Upvotes: 0
Views: 62
Reputation: 80781
The only order that is guaranteed here is that 4 will happen after 2, and 3 will happen after 1. This is because both your custom queue and the main queue are serial – and therefore blocks are executed in the order in which they were scheduled.
However, because your serialQueue
is executing blocks on a background thread (try logging the current thread) – your 1 and 3 operations are happening concurrently with your 2 and 4 operations.
Therefore the exact ordering between the operations on your serial queue and operations on the main queue is undefined.
If you changed your dispatch_async
to dispatch to the main queue, then you'll indeed get the ordering you want (2, 4, 1, 3) – as the blocks you schedule will have to wait for the main queue to finish executing it's current task (your 2 and 4 operations + whatever else the main queue is doing).
Upvotes: 2