Junior — Middle
How to distinguish a thread of execution from a coroutine and what are the main differences between them?
sobes.tech AI
Answer from AI
A thread is a separate control flow that runs concurrently with other threads, has its own stack and system resources. Threads are usually managed by the operating system and can run simultaneously on different CPU cores.
A coroutine is a lightweight function that can suspend its execution (yield) and resume later, allowing efficient management of asynchronous tasks without creating new threads. Coroutines operate within a single thread and switch cooperatively, meaning control is explicitly transferred.
Main differences:
- Threads are system-level, coroutines are user-level (lightweight).
- Threads can run in parallel on multiple cores, coroutines run sequentially within one thread.
- Threads require synchronization to access shared resources, coroutines usually avoid races as switching is explicit.
Example in Kotlin (Android):
// Thread
Thread {
println("Execution in a separate thread")
}.start()
// Coroutine
GlobalScope.launch {
println("Execution in a coroutine")
}