Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift code suspension point in asynchronous & synchronous code

I keep reading that synchronous function code runs to completion without interruption but asynchronous functions can define potential suspension points via async/await. But my question is why can't synchronous function code be interrupted at any point, can't the OS scheduler suspend the thread/process at any point and give CPU to a higher priority thread/process (just like it happens in any OS)? What am I understanding wrong here?

like image 233
Deepak Sharma Avatar asked Oct 26 '25 14:10

Deepak Sharma


1 Answers

Your intuition here is correct. The structured concurrency system does not interrupt synchronous code. But the thread scheduler, and also GCD queues, are independent of that. This is a major reason to be very careful mixing structured concurrency (async/await) and GCD or traditional threads. You should think of structured concurrency as providing a higher-level abstraction over the threading system.

And definitely, all of this is only valid within a process space. The OS is absolutely capable of suspending the process.

This is very similar to the fact that one might say a let constant is immutable, but it is possible to write code that violates that by writing directly to memory, the OS can even directly change the variable from outside the process (this is how debuggers work). It is "immutable" only in terms of Swift rules. The system is certainly able to modify the memory.

But within the structured concurrency abstraction, you can be sure that suspension will only occur at certain points, and the compiler will help make this illusion as strong as it can, particularly if you enable Strict Concurrency checking.

Alexander's comments made me remember another important point: Threads are useful even when there is only one CPU. They are fundamentally about concurrency, not parallelism. They permit logically distinct operations to run independently on the same CPU. Similarly, Tasks are useful even if there were only one thread. They permit logically distinct operations to run independently on the same thread. This is especially interesting when considering Swift on embedded devices which may not even support multiple threads. For more on the history that led to Swift's concurrency model, search for "coroutines." While Swift Concurrency has some unique features, at its heart it's based on decades of work in coroutines.

like image 77
Rob Napier Avatar answered Oct 29 '25 05:10

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!