Suppose I call dispatch_async() three times in order:
dispatch_async(dispatch_get_main_queue(),
^{
[self doOne];
});
// some code here
dispatch_async(dispatch_get_main_queue(),
^{
[self doTwo];
});
// more code here
dispatch_async(dispatch_get_main_queue(),
^{
[self doThree];
});
Will this always be executed like
[self doOne], [self doTwo], then [self doThree], or is the order is guaranteed?
In this case, the question probably is if the main queue is serial or concurrent.
From the documentation:
dispatch_get_main_queue
Returns the serial dispatch queue associated with the application’s
main thread.
so the main queue is a serial queue, and [self doOne], [self doTwo], [self doThree] are executed sequentially in that order.
Concurrency Programming Guide, About Dispatch Queues:
The main dispatch queue is a globally available serial queue that executes tasks on the application’s main thread. [emphasis mine]
Related
I'm trying to understand queue in iOS; with this code
dispatch_queue_t coda_thread=dispatch_queue_create("coda_thread",NULL);
//UIPROGRESS VIEW
for(i=0;i<=10;i=i+1)
{
dispatch_async(coda_thread,
^{
NSLog(#"CODA_THREAD");
NSLog(#"attendo..");
[NSThread sleepForTimeInterval:10];
dispatch_async(dispatch_get_main_queue(),
^{
NSLog(#"MAIN THREAD");
NSLog(#"aggiorno barra..");
[self.upv setProgress:i/10 animated:YES];
});
});
}
I expected no freeze in GUI because sleep is in coda_thread (and not in main queue where is updated the GUI) queue while setProgress in main queue.. Instead I have freeze in my GUI..why this?
The problem is that a dispatch queue is not a new thread. You have no guarantee that the dispatch queue is actually using a different thread. Combining GCD API with thread API just won't work.
I am aware that calling dispatch_async in the current queue will cause a deadlock, however, experiencing a deadlock in a completely different queue:
-(void) deadlock{
// we reach this point in the main queue
dispatch_sync(dispatch_queue_create("lucas", 0), ^{
NSLog(#"Doing something in the bakcgound...");
// We reach this point in another queue, but it deadlocks!
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Will I ever get here?????");
});
});
}
Any idea of what I'm doing wrong??
Yes, it's a deadlock. Just like you have been creating an example of one
-(void) deadlock{
// we reach this point in the main queue
//and so main queue waits till this task will finish
dispatch_sync(dispatch_queue_create("lucas", 0), ^{
//doing something in background
//while main queue still blocked by that dispatch_sync() call
NSLog(#"Doing something in the bakcgound...");
// We reach this point in another queue, but it deadlocks!
//Of cause it does!!! Main queue is still waiting till task dispatched to "lucas" queue synchronously finishes. But it can't - waits for main queue to perform this later bock synchronously
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Will I ever get here?????");
});
});
}
//we reach this point only after all code written above will performed. so, in our case, this point is unreachable either way
So, dependently on your task, you should change one of this dispatch_sync() to dispatch_async().
Dispatch_sync is semantically equivalent to a traditional mutex lock, rather than creating a thread. Try the following, will give you: "Is main thread: 1".
dispatch_sync(dispatch_queue_create("lucas", 0), ^{
NSLog(#"Doing something in the bakcgound...");
NSLog(#"Is main thread: %d", [NSThread isMainThread]);
// We reach this point in another queue, but it deadlocks!
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Will I ever get here?????");
});
});
What you want I think is more or less the following:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSLog(#"Doing something in the bakcgound...");
dispatch_async(dispatch_get_main_queue(), ^(void){
NSLog(#"Will I ever get here?????");
});
});
Is there any difference between if dispatch_sync is called in 3 different queue like
1.
dispatch_sync(dispatch_get_main_queue(),^(void){
NSLog(#"this execute in main thread") // via [NSThread isMainThread]
});
2.
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){
NSLog(#"this also execute in main thread") // via [NSThread isMainThread]
}
3.
dispatch_queue_t queue;
queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_sync(queue, ^(void){
NSLog(#"this also execute in main thread") // via [NSThread isMainThread]
}
Whenever i call dispatch_sync, block executed in main thread, without considering in which queue it is dispatched. So why this function take queue as a argument as it doesn't use it. Can someone please clarify this?
dispatch_sync is a blocking operation. That is, the function will not return until the work represented in the block is completed.
When dispatched to an asynchronous queue -- like one of the global queues or a concurrent queue of your own making -- there is no reason to do anything but invoke the block on the thread that called dispatch_sync(). Even in the case of invoking the block on a synchronous queue, the dispatch_sync() is going to wait until completion anyway so, internally, it might as well stop until the rest of the work is done in the queue and then execute the block directly.
As it turns out, passing data from thread A to thread B is expensive. If the queue is in the state where execution can happen immediately, then dispatch_sync will fast path the execution by simply calling the block on the thread that dispatch_sync was called on.
And, by definition, you shouldn't care. The calling thread is blocked -- can't do a thing -- until dispatch_sync() returns.
So, really, all of this is an implementation detail. GCD is free to execute the blocks on whatever threads it deems most appropriate. It just so happens that don't context switch is often the most important rule of figuring that out.
See dispatch_sync documentation, which notes
As an optimization, this function invokes the block on the current thread when possible.
If you dispatch something synchronously, since the thread must wait for the dispatched code to complete, anyway, it will frequently run that code on the current thread. So if dispatched synchronously from the main thread, it will run on main thread. If dispatched synchronously from a background thread, it will run on that background thread.
As noted by ipmcc, a well-known exception is when a background thread dispatches something synchronously to the main thread. As the libdispatch source says:
It's preferred to execute synchronous blocks on the current thread
due to thread-local side effects, garbage collection, etc. However,
blocks submitted to the main thread MUST be run on the main thread.
For your problem: you call the dispatch_sync always in main queue, and if you wanna know why, see the following:
At first you need to pay attention to the description on of "dispatch_sync"
Submits a block to a dispatch queue for synchronous execution. Unlike dispatch_async,
this function does not return until the block has finished.
Calling this function and targeting the current QUEUE(NOT THREAD) results in deadlock.
#define logStep(step,queue) NSLog(#"step: %d at thread: %# in -- queue: %s",step,[NSThread currentThread],dispatch_queue_get_label(queue));
// call the method in main thread within viewDidLoad or viewWillAppear ...
- (void)testDispatchSync{
//let's distinctly tell the 4 queues we often use at first
self.concurrentQ = dispatch_queue_create("com.shared.concurrent", DISPATCH_QUEUE_CONCURRENT);
self.serialQ = dispatch_queue_create("com.shared.serial", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t mainQ = dispatch_get_main_queue();
dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
logStep(1,mainQ) //we're in main thread and main queue, current queue IS main queue
// do a sync in main thread & concurrent queue
dispatch_sync(_concurrentQ, ^{
logStep(2,_concurrentQ)
});
// do a sync in main thread & serial queue
dispatch_sync(_serialQ, ^{
logStep(3,_serialQ)
});
//uncommenting the following code that you'wll see a crash will occur, because current queue is main queue
// dispatch_sync(mainQ, ^{
// logStep(4, mainQ)
// });
dispatch_async(_concurrentQ, ^{
// inside of the this scope, current queue is "_concurrentQ"
logStep(11,_concurrentQ)
// using sync in any queue here will be safe!
dispatch_sync(_concurrentQ, ^{
logStep(12,_concurrentQ)
});
dispatch_sync(_serialQ, ^{
logStep(13,_concurrentQ)
});
dispatch_sync(mainQ, ^{
logStep(14,mainQ)
});
dispatch_sync(globalQ, ^{
logStep(15,globalQ)
});
// using async in any queue here will be safe!
dispatch_async(_concurrentQ, ^{
logStep(111,_concurrentQ)
});
dispatch_async(_serialQ, ^{
logStep(112,_concurrentQ)
});
dispatch_async(mainQ, ^{
logStep(113,mainQ)
});
dispatch_async(globalQ, ^{
logStep(114,globalQ)
});
});
dispatch_async(_serialQ, ^{
// inside of the this scope, current queue is "_serialQ"
logStep(21,_serialQ)
// using async in any queue except current queue here will be safe!
dispatch_sync(_concurrentQ, ^{
logStep(22,_concurrentQ)
});
dispatch_sync(mainQ, ^{
logStep(23,mainQ)
});
dispatch_sync(globalQ, ^{
logStep(24,globalQ)
});
//uncommenting the following code that you'wll see a crash will occur, because current queue is "_serialQ"
// dispatch_sync(_serialQ, ^{ //app will die at here
// logStep(25,_serialQ)
// });
});
}
So we got the conclusion:
the key problem is that thread will be blocked while "dispatch_sync" running on current queue which is a serial queue at the same time.
main queue is also a serial queue so that it explained why you cann't call dispatch_sync in main thread
If I do this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self someMethod];
});
And someMethod is this:
-(void)someMethod{
//doing stuff with no mention of GCD
}
Will someMethod run inside the dispatch queue, or will that queue wait for someMethod to run on the main thread, since someMethod does not itself dispatch anything to other queues?
Methods are executed on the thread or queue from which they are invoked. So, if you wanted to update UI after processing data on a background queue, you'd need to explicitly execute your UI update on the main thread.
For example:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self someMethod];
});
- (void) someMethod{
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI here
});
}
I'm trying to perform the acquisition of data from the internet on the load of my view. To not lag the UI, I'm performing the HTML download and parsing by using
[self performSelectorInBackground:#selector(alertThreadMethod) withObject:nil];
which checks to see if there is an alert online. In order to display the information on the view however, iOS says that I need to use the main thread. So i call the display code right after:
[self performSelectorInBackground:#selector(alertThreadMethod) withObject:nil];
[self loadAlert];
In doing this, the [self loadAlert]; actually runs before the selector in the background (it is faster). Because of this, it does not have the information that the selector in the background is supposed to provide it.
How can I ensure that [self loadAlert]; runs after? Or is there a better way to do this?
You can either move loadAlert invocation into the alertThreadMethod or use Grand Central Dispatch serial queues, e.g.,
dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
[self alertThreadMethod];
[self loadAlert];
});
dispatch_release(queue);
Or, if loadAlert is updating the UI, since you do UI updates in the main queue, you'd do something like:
dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
[self alertThreadMethod];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAlert];
});
});
dispatch_release(queue);
By the way, if you're just doing this one task in background, rather than creating your own serial queue, you might just use one of the existing background queues. You only need to create a queue if you need the serial nature (i.e. you're going to be numerous dispatch_async calls and you can't have them running concurrently). But in this simple case, this might be even a little more efficient, bypassing the creating and releasing of the serial queue:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[self alertThreadMethod];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAlert];
});
});
In your alertThreadMethod, after you have your information, call the method performSelectorOnMainThread:withObject:waitUntilDone: and pass it a selector to your loadAlert method.
-(void)alertThreadMethod
{
// get your information here
performSelectorOnMainThread:#selector(loadAlert) withObject:nil waitUntilDone:NO
}