User-level

Process- and thread-based concurrency are limited by how many of them we can spawn. A lighter and more efficient alternative is to use user space threads, popularly known as green threads. They first appeared in Java with the code name green and the name has stuck since then. Other languages such as Go (goroutines), and Erlang also have green threads. The primary motivation in using green threads is to reduce the overhead that comes with using process- and thread-based concurrency. Green threads are very lightweight to spawn and use less space than a thread. For instance, in Go, a goroutine takes only 4 KiB of space compared to the usual 8MB by a thread.

User space threads are managed and scheduled as part of the language runtime. A runtime is any extra bookeeping or managing code that's executed with every program you run. This would be your garbage collector or the thread scheduler. Internally, user space threads are implemented on top of native OS threads. Rust had green threads before the 1.0 version, but they were later removed before the language hit stable release. Having green threads would have steered away Rust's guarantee and its principle of having no runtime costs.

User space concurrency is more efficient, but hard to get right in its implementation. Thread-based concurrency, however, is a tried and tested approach and has been popular since multi-process operating systems came into existence and it's the go- to approach for concurrency. Most mainstream languages provide threading APIs that allows users to create threads and easily offload a portion of their code for independent execution.

Leveraging concurrency in a program follows a multi-step process. First, we need to identify parts of our problem that can be run independently. Then, we need to look for ways to co-ordinate threads that are split into multiple sub-tasks to accomplish a shared goal. In the process, threads might also need to share data and they need synchronization for accessing or writing to shared data. With all of the benefits that concurrency brings with it, there are a new set of challenges and paradigms that developers need to care and plan for. In the next section, let's discuss the pitfalls of concurrency.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset