Reputation: 655
I learning Concurrency programming topic in ios. I did a sample application for multiple serial dispatch queue.
-(IBAction)SerialDispatchAction:(id)sender
{
s1queue = dispatch_queue_create( "com.newtok.firstQueue" , NULL);
s2queue = dispatch_queue_create( "com.newtok.secondQueue" , NULL);
dispatch_async(s1queue, ^{
int i=0;
while(i<5)
{
printf("First Asynchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
dispatch_async(s2queue, ^{
int i=0;
while(i<5)
{
printf("Second Asynchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
dispatch_sync(s1queue ,^{
int i=0;
while(i<5)
{
printf("First Synchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
dispatch_sync(s2queue ,^{
int i=0;
while(i<5)
{
printf("Second Synchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
}
I read ,if you are creating multiple Dispatch serial queue , the queues are running concurrently. i got the out put like this....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
What is the difference between dispatch_async and dispatch_sync? How it dip pent each other?
Upvotes: 1
Views: 1957
Reputation: 359
If you print out [NSThread currentThread], you may understand dispatch_sync sometimes optimizes to run on current thread - not multiple threads. In your example, dispatch_sync runs on main thread in deed, so you find the results are serialized.
Upvotes: 0
Reputation: 3266
dispatch_sync() blocks and also ensures that all items on the queue have finished running before it returns. dispatch_async() simply submits the block and returns immediately. Whether the block then runs concurrently or serially depends on which kind of queue you have submitted the work to. As you have correctly surmised, multiple serial queues will run concurrently with respect to one another (as opposed to the individual blocks on the queue running concurrently, as they will with a concurrent queue).
Upvotes: 1
Reputation: 1904
dispatch_sync
will block thread until it's done, dispatch_async
submit blocks to run concurrently. I'd recommend you to re-read apple docs on GCD and this article.
Upvotes: 1