What is a synchronous function?
What is a synchronous function? êŽë š
Updated for Xcode 15
By default, all Swift functions are synchronous, but what does that mean?
A synchronous function is one that executes all its work in a simple, straight line on a single thread. Although the function itself can interact with other threads â it can request that work happens elsewhere, for example â the function itself always runs on a single thread.
This has a number of advantages, not least that synchronous functions are very easy to think about: when you call function A, it will carry on working until all its work is done, then return a value. If while working, function A calls function B, and perhaps functions C, D, and E as well, it doesnât matter â they all will execute on the same thread, and run one by one until the work completes.
Internally this is handled as a function stack: whenever one function calls another, the system creates whatâs called a stack frame to store all the data required for that new function â thatâs things like its local variables, for example. That new stack frame gets pushed on top of the previous one, like a stack of Lego bricks, and if that function calls a third function then another stack frame is created and added above the others. Eventually the functions finish, and their stack frame is removed and destroyed in a process we call popping, and control goes back to whichever function the code was called from.
Synchronous functions have an important downside, which is that they are blocking. If function A calls function B and needs to know what its return value is, then function A must wait for function B to finish before it can continue. This sounds self-evident, I know, but blocking code is problematic because now youâve blocked a whole thread â it might be sitting around for a second or more waiting for some data to return.
Youâre probably thinking that waiting for a second is nothing at all, but in computing terms thatâs an ice age! Keep in mind that the Neural Engine in Appleâs A14 Bionic CPU â just one part of the chip that powers the iPhone 12 â is capable of doing 11 trillion things per second, so if you block a thread for even a second thatâs 11,000,000,000,000 things you could have done but didnât.
One solution is to say âWell, if weâve got a thread thatâs currently blocked, we should just launch a new thread.â Thatâs definitely a solution, but itâs also a path towards thread explosion and weâve already covered why thatâs every bit as bad as it sounds.
So, although synchronous functions are easy to think about and work with, they arenât very efficient for certain kinds of tasks. To make our code more flexible and more efficient, itâs possible to create asynchronous functions instead.