ShinehahGnolaum wrote:
So where does synchronous and asynchronous fit it? What are the differences between those two things?
I assume this is in reference to the GCD "dispatch_sync" and "dispatch_async" functions. Unfortunately, this is just poor function naming on Apple's part. It leads to a lot of confusion.
Synchronous means multiple things happening at the same time. Ergo, "dispatch_sync" means exactly the opposite of what it should mean. 🙂
Asynchronous is not quite the opposite of that, at least in a computing concept. I think Apple must have created "dispatch_async" first and then somebody decided to use "dispatch_sync" for something that was the opposite. But that only boxed them into a semantic mess.
In a computing context, asynchronous is closer to the concept of "event-driven". Obviously, event-driven means something that happens in response to an event. But the key part of this is that both event-driven and asynchronous refer to operations that happen on some undefined schedule that you, the programmer, do not control. You don't know when the user is going to click a mouse button, when a hardware interrupt is going to fire, or when your asychronously dispatched block is going to execute. Therefore, think of asynchonous as meaning "you don't know when".
Synchonrous is then the opposite of that - "you know exactly when". When you dispatch a block synchronously, you know it is going to execute right then and there.
It is important that you don't equate "asynchronous" with "concurrent". They are not the same. When you are running code, you will often notice that code that is written after "dispatch_async" actually executes before the block inside the "dispatch_async" function call. That is an illusion. It could happen before, at the same time, or 5 minutes later. You don't know when the code in the asynchronous block is going to execute.
But with dispatch_sync, the code will execute in the order specified by the code. I am going to have to take issue with one of the previous replies. You almost never want to do UI updates via dispatch_sync. UI updates should only happen on the main thread, which just happens to be a serial queue. Normally you perform a dispatch_async on the main thread and then let your background thread run. You can also call dispatch_async on the main thread from the main thread. Don't try that with dispatch_sync or you'll deadlock.
There is no such thing as a "thread-unsafe data strucure" because there are only "data structures" and none of them are ever thread safe. A dispatch_sync function is useful, along with a serial queue, for ensuring that only one threat at a time has access to a data structure. If you do happen to have some object that is advertised as "thread safe", it is only because someone else has done the work with "dispatch_sync" or an equivalent to ensure that you can safely access it from multiple threads. If you aren't careful with dispatch_sync, you could have deadlock, which is bad.