Coroutines
-
Lightweight coroutine.
Launching coroutines and switching between them is extremely fast. It requires only a few machine instructions. This makes coroutines a suitable basic flow control mechanism, like the
if
orwhile
keywords, which have comparable performance.Coroutines have one big limitation, though: All coroutines run on a single CPU core. If you want to take advantage of multiple cores, you have to launch multiple threads or processes, presumably as many of them as there are CPU cores on your machine.
Coroutines are scheduled cooperatively. What that means is that a coroutine has to explicitly yield control of the CPU to allow a different coroutine to run. In a typical scenario, this is done transparently to the user: When a coroutine invokes a function that would block (such as
Coroutine.wakeUp
,FileDescriptor.poll
,channel.send
orchannel.receive
), the CPU is automatically yielded. However, if a coroutine runs without calling any blocking functions, it may hold the CPU forever. For these cases, theCoroutine.yield
function can be used to manually relinquish the CPU to other coroutines manually.Example:
See morelet coroutine = try Coroutine { ... } coroutine.cancel()
Declaration
Swift
public final class Coroutine