PDA

View Full Version : Any chance for dead-lock ?




namanhams
Sep 13, 2012, 11:52 PM
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}


Given that block() just doesn't do anything with GCD (eg, it doesn't dispatch any block).

Is there any chance that the above code snippet can cause a dead-lock ?
From my understanding it can't, but i just want it to be confirmed.



Duncan C
Sep 14, 2012, 08:26 PM
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}


Given that block() just doesn't do anything with GCD (eg, it doesn't dispatch any block).

Is there any chance that the above code snippet can cause a dead-lock ?
From my understanding it can't, but i just want it to be confirmed.

It's a little hard to figure out what you're asking from that little snippet.

I gather that block() is a code block, and that you have code that could be run from the main thread or from a background thread. You're trying to run block() on the main thread in either case. If you're currently running in the main thread, you execute the block directly. Otherwise, you submit the block to the main thread's primary dispatch queue synchronously.

You could cause a deadlock if the main thread is currently waiting for a response from the thread where this code is being executed (e.g. from another dispatch_sync). In that you'll deadlock with the main thread waiting on the second thread and the second thread waiting on the main thread.

namanhams
Sep 16, 2012, 11:25 PM
It's a little hard to figure out what you're asking from that little snippet.

I gather that block() is a code block, and that you have code that could be run from the main thread or from a background thread. You're trying to run block() on the main thread in either case. If you're currently running in the main thread, you execute the block directly. Otherwise, you submit the block to the main thread's primary dispatch queue synchronously.

You could cause a deadlock if the main thread is currently waiting for a response from the thread where this code is being executed (e.g. from another dispatch_sync). In that you'll deadlock with the main thread waiting on the second thread and the second thread waiting on the main thread.

Your guess is right. I'm trying to run the block on the main thread.
Thanks for pointing out the scenario. I think that's the only case where a deadlock can happen :cool: