Thanks for signing up.
We'll see you soon 👋
We'll see you soon 👋
Have you heard of Routine or Subroutine in programming languages? It simply means functions or methods . Co-Routines means cooperative routines . i.e routines which cooperate with each other . It means when one routine is executing the other routine will not interfere with 1st coroutine w.r.t to memory , cpu ,any resource by suspending itself i.e without blocking. I will talk about suspend and blocking a little later , please hold on ! Coroutines are supported by many languages such as Kotlin ,C++(20 onwards), java scripts ,etc . The concept of coroutine is almost the same across all languages , but there will be some differences. Here I will talk more about the Kotlin coroutine but the concepts remain the same across all languages .
Why are Coroutines required , is thread or process not enough ?
Coroutines are lightweight compared to Process and Threads . Wait a minute what you mean by light or heavy weight ?
Note : Below are w.r.t unix/Linux ( The definition of process , task , thread may differ based on the OS or platform )
Thread creation is the same as a process at the kernel level since both are represented as tasks(task_struct ) at the kernel level and creation is done using clone(). Linux implements all threads as standard processes. Thread is merely a process that shares certain resources with other processes (which just happens to share resources, such as an address space(DS,heap , signal action , FD,etc ), with other processes). Threads are created at the user space by pthread_create() (Posix call) Ex: pthreadcreate(pthreadt threadid,pthreadattr_t attributes, void (ThreadFunction)(void), void* ThreadParamToBePassedToThreadFunction) One process contains at least one thread and can contain more than one thread. Please note that threads within the same process have separate stack , cpu registers ,program counter etc .Conclusion : Thread creation is much cheaper compared to process.
In android, if the main or UI thread cannot finish executing blocks of work within 16ms, the user may observe hitching, lagging, or a lack of UI responsiveness to input. If the main thread blocks for approximately five seconds, the system displays the Application Not Responding (ANR) dialog, allowing the user to close the app directly. So the solution for the above problem is async programming. i.e don't block the main thread . Delegate the heavy work out of the main thread using any of the below: Threads Futures and Promises Async task (deprecated from Android 11) Reactive Extensions (Rx) Coroutines <– Lets talk about this !
Coroutines are lighter than threads . Since they stack less . I.e coroutines don't have a dedicated stack . It means coroutine suspend execution by returning to the caller and the data that is required to resume execution is stored separately from the stack. This allows for sequential code that executes asynchronously (e.g. to handle non-blocking I/O without explicit callbacks). In an android environment specially in phones where there is constraint for memory , cpu , battery and app response to user action is very critical. Coroutines are light-weight threads & Using coroutines can remove callbacks. In Kotlin coroutines can be launched with launch,async ,runBlocking, withcontext coroutine builder in a context of some CoroutineScope. . By default, coroutines are run on a shared pool of threads. Please note that Threads still exist in a program based on coroutines. One thread can run many coroutines, so there's no need for too many threads. One Coroutine may run many threads i.e. shared pool of threads .and also many coRoutines can run one threads. Coroutine doesn't have a dedicated stack, they share the stack due to support for suspension,. Coroutine offers fewer memory leaks due to use of structured concurrency i.e It is a way to structure async/concurrent tasks so that child operations are guaranteed to complete before their parents, i.e. no child operation is executed beyond the scope of a parent scope. That means coroutines can be only launched in a specific CoroutineScope. And also cancellation is propagated automatically through the running coroutine hierarchy i.e from parent to all the children. Coroutines solve problems of callback such as complexity in readability of code due to many callbacks & also some language dony support the exception handling in callbacks. Under the hood of coroutine -> How are Coroutines built ? Coroutines build upon regular functions by adding two new operations in addition to invoke (or call) and return, coroutines as below :
Coroutines can be used for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines enable you to write clean, simplified asynchronous code that keeps your app responsive while managing long-running tasks. Coroutines are well-suited for implementing familiar program components such as cooperative tasks, exceptions, event loops, iterators, infinite lists and pipes.
Please see my next article about details of Kotlin Coroutine creation , usage and various concepts. Please comment if you have anything to add or modify . Thank you for reading !
Originally published on www.linkedin.com
Engineers who find a new job through Functional Works average a 15% increase in salary.Start with GitHubStart with TwitterStart with Stack OverflowStart with Email