<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aanchalsethi on Medium]]></title>
        <description><![CDATA[Stories by Aanchalsethi on Medium]]></description>
        <link>https://medium.com/@aanchalsethi1409?source=rss-e0521c1c639d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*23TiNP3MPnVCOcQ9.jpg</url>
            <title>Stories by Aanchalsethi on Medium</title>
            <link>https://medium.com/@aanchalsethi1409?source=rss-e0521c1c639d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:01:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aanchalsethi1409/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Thread Scheduling: Optimizing Concurrency with Go Fiber]]></title>
            <link>https://medium.com/@aanchalsethi1409/thread-scheduling-optimizing-concurrency-with-go-fiber-4bdc1fceabcb?source=rss-e0521c1c639d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bdc1fceabcb</guid>
            <dc:creator><![CDATA[Aanchalsethi]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 11:11:34 GMT</pubDate>
            <atom:updated>2024-10-10T11:11:34.043Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In today’s fast-paced world of computing, making sure that tasks are handled efficiently is critical. Whether you’re running a simple app on your phone or a large-scale service like a web server, how tasks are managed behind the scenes can significantly impact performance.This blog explores fundamental concepts of thread scheduling essential for ensuring smooth and efficient task management.</p><p>A thread is a single sequence of execution within a process. To put it simply, a thread is like a worker doing one specific job in a company. These workers can perform tasks at the same time, which speeds things up. Each thread belongs to exactly one process and can run in parallel with other threads, significantly enhancing application performance. Additionally, threads can share common data, simplifying task coordination by eliminating the need for complex inter-process communication.</p><p><strong>Importance of Scheduling</strong></p><p>To understand why scheduling is crucial in computing, we first need to grasp the difference between two types of tasks: CPU-bound and I/O-bound tasks.</p><p>CPU-bound tasks require a lot of processing power and keep the CPU busy without much delay. Think of it as a chef who is constantly cooking without having to wait for ingredients to arrive. The CPU is effectively utilized because it is always working.</p><p>In contrast, I/O-bound tasks are like a chef waiting for ingredients to be delivered. During these tasks, the CPU often finds itself idly waiting for input or output operations to finish, such as reading from a disk or waiting for a network response. This downtime can be a wasted opportunity; the CPU could be working on something else instead.</p><p>Now, let’s visualize a scenario involving an I/O-bound task. Imagine a server processing multiple requests. If each request is handled one at a time, the CPU will sit idle during I/O waits — wasting valuable time that could be spent processing other requests. This is where scheduling comes into play.</p><p>By allowing tasks to run concurrently, the operating system can ensure that while one task is waiting for I/O, the CPU can jump to another task. For example, if one request is fetching data from a database, the server can immediately start processing another request instead of twiddling its thumbs. This not only keeps the CPU busy but also speeds up the overall performance of applications.</p><p>Efficient scheduling is key to making the most of these opportunities, ensuring that no CPU cycles go to waste. As applications become more complex and handle more tasks simultaneously, robust scheduling strategies become essential for maintaining optimal performance and responsiveness.</p><p><strong>Relating This to Go Fiber: A Practical Example</strong></p><p>Let’s connect these ideas with a real-world example. Imagine you’re building a web server using Go Fiber, a popular framework in Golang. One of the biggest challenges when handling many requests at once is making sure all requests get processed efficiently. This is where thread scheduling comes in. By effectively managing threads, Go Fiber can handle multiple requests without wasting resources.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br><br> &quot;github.com/gofiber/fiber/v2&quot;<br>)<br><br>func main() {<br> app := fiber.New()<br><br> // ProcessOrder simulates an order processing task with concurrency<br><br> app.Get(&quot;/process&quot;, func(c *fiber.Ctx) error {<br>  for i := 1; i &lt;= 5; i++ {<br>   go processOrder(i)<br>  }<br>  return c.SendString(&quot;Orders are being processed concurrently&quot;)<br> })<br><br> app.Listen(&quot;:3030&quot;)<br>}<br><br>// processOrder simulates a task that takes time to process<br>func processOrder(orderID int) {<br><br> fmt.Printf(&quot;Processing order %d...\n&quot;, orderID)<br> <br>// Simulate time-consuming task<br> time.Sleep(2 * time.Second)<br> fmt.Printf(&quot;Order %d processed!\n&quot;, orderID)<br>}</pre><p>In this example, when the /process route is hit by an HTTP request, a time-consuming task is initiated (simulated by a time.Sleep(5 * time.Second) call). However, the task is processed in a separate goroutine using the go keyword. This way, the web server can continue to handle other incoming requests immediately without waiting for the first task to complete.</p><p>Since each request is handled concurrently in its own goroutine, the server is able to respond to multiple requests at once, even when one of them involves a long-running operation. This non-blocking behavior is crucial in web applications where you don’t want users to experience delays just because one request is taking a long time to process.</p><p>This example illustrates how Go Fiber takes advantage of Go’s concurrency mechanisms to manage thread-like behavior. By spawning goroutines for tasks, it mimics efficient thread scheduling, where multiple threads (or in this case, goroutines) are running in parallel, maximizing CPU usage and improving the server’s overall responsiveness.</p><p>This approach highlights Go’s ability to handle high concurrency efficiently, making it a great choice for building high-performance web servers.</p><p><strong>Thread Scheduling</strong></p><p>Thread scheduling is a vital aspect of operating system design, allowing for the efficient management of multiple execution paths within a process. There are two main approaches to managing threads: <strong>user-level threads (ULT)</strong> and <strong>kernel-level threads (KLT)</strong>. Understanding how each of these works helps optimize application performance and resource usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*omvNPwssBNd_fC4n" /></figure><p>In the above scenario, the kernel has allocated a single kernel thread to a process with three user-level threads. These user-level threads take turns executing on the same kernel thread. When one of the threads makes a blocking system call, both that thread and the kernel thread it was using become blocked. To ensure the process continues running, the kernel initiates a scheduler activation, allocating a new kernel-level thread to the process. Through an upcall, the kernel informs the user-level thread manager about the blocked thread and the availability of the new kernel thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*IexZzctw7cCCHuNp" /></figure><p>The user-level thread manager then moves the remaining threads to the new kernel thread, resuming one of the ready threads. While the blocked thread remains in the waiting state, the other threads can continue executing on the newly allocated kernel thread, ensuring efficient task execution without unnecessary delays.</p><p><strong>User-level threads (ULT)</strong></p><p>User-level Threads (ULT) are managed entirely by the application, without involving the operating system. The application handles the creation, scheduling, and synchronization of these threads, making them faster and more lightweight compared to kernel-level threads. Context switching between ULTs is efficient since it happens within the application itself, without needing the operating system’s intervention.</p><p>For example, web servers handling multiple client requests can use ULTs, allowing the application to manage switching between requests. This reduces the overhead involved in frequent context switching and gives the application full control over the flow of execution. However, ULTs have a significant drawback: if one thread performs a blocking operation like waiting for I/O, the entire process gets blocked because the operating system is unaware that other threads are ready to execute. This can lead to inefficiencies, particularly in I/O-bound applications, which is where kernel-level thread (KLT) management becomes necessary.</p><p>Goroutines in Go are an example of ULTs. They are lightweight user-space constructs that allow functions to run concurrently without requiring kernel-level threads.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>// Function that simulates user-level threading via goroutines<br>func processTask(taskID int) {<br> fmt.Printf(&quot;Processing task %d\n&quot;, taskID)<br> // Simulating work<br> time.Sleep(1 * time.Second) }<br><br>func main() {<br> for i := 1; i &lt;= 5; i++ {<br>  // Launches a user-level thread (goroutine)<br>  go processTask(i)  <br>}<br><br> // Wait for goroutines to finish<br>time.Sleep(2 * time.Second)<br> fmt.Println(&quot;All tasks completed&quot;)<br>}</pre><p>In this example, each processTask function runs concurrently using <strong>goroutines</strong>, which are user-level threads managed by the Go runtime. You can run thousands of goroutines with minimal overhead compared to kernel-level threads.</p><p><strong>Kernel-level threads (KLT)</strong></p><p>Kernel-level threads are managed directly by the operating system. Each thread has its own stack, register set, and execution context, and the OS handles their scheduling. KLTs are more resource-intensive than user-level threads due to the overhead of context switching, which requires interaction with the kernel.</p><p>KLTs are ideal for CPU-intensive tasks, such as scientific simulations or video encoding, where the operating system can assign different threads to multiple processors, enabling true parallelism. They are also more efficient in handling I/O-bound tasks, as the OS can switch to another thread if one is waiting for I/O, keeping the CPU busy.</p><p>In Go, while goroutines are lightweight, user-level threads, the Go runtime maps them to kernel threads using an M-scheduling model, where many goroutines are distributed across fewer kernel threads.</p><p>The following example demonstrates how Go uses kernel-level threads through the runtime.GOMAXPROCS function, which controls the number of OS threads:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;runtime&quot;<br> &quot;time&quot;<br>)<br><br>func processTask(taskID int) {<br> fmt.Printf(&quot;Processing task %d\n&quot;, taskID)<br> // Simulating work<br> time.Sleep(1 * time.Second)<br>}<br><br>func main() {<br> // Limit to 2 kernel-level threads<br> runtime.GOMAXPROCS(2)<br> for i := 1; i &lt;= 5; i++ {<br>  go processTask(i)<br> }<br><br> time.Sleep(3 * time.Second)<br> fmt.Println(&quot;All tasks completed&quot;)<br>}</pre><p>Here, runtime.GOMAXPROCS(2) limits Go to use a maximum of 2 kernel threads. The Go runtime handles the mapping of goroutines to kernel threads, allowing for efficient concurrency without the developer managing kernel threads directly.</p><p><strong>Scheduling Boundaries in Real-Time Systems</strong></p><p>In real-time systems, thread scheduling involves more than simply choosing policies and priorities. Two key controls — contention scope and allocation domain — play crucial roles in scheduling user-level threads:</p><ol><li><strong>Contention Scope:</strong></li></ol><ul><li>Process Contention Scope (PCS): Limits competition for CPU resources to threads within the same process.</li><li>System Contention Scope (SCS): Allows competition across all threads within the system.</li></ul><p>In PCS, for example, a process managing multiple threads (like a media player processing audio and video) will restrict contention to its own threads. In SCS, on the other hand, threads from different processes (like a browser and a video player) may compete for the same CPU resources.</p><p><strong>2. Allocation Domain:</strong></p><p>The allocation domain refers to the set of resources (such as cores in a multicore system) for which a thread competes. A single ULT can belong to multiple allocation domains, depending on the system’s architecture and the application’s complexity.</p><p><strong>Conclusion</strong></p><p>In modern software development, efficient thread scheduling is critical to ensuring smooth, responsive applications. Whether managing CPU-bound or I/O-bound tasks, the ability to switch between threads, optimize CPU usage, and handle multiple requests concurrently enhances overall performance. Go Fiber, with its lightweight goroutines and built-in concurrency model, makes it easy to achieve this, offering developers a powerful tool to handle multiple tasks in parallel without being bogged down by the complexities of thread management.</p><p>By understanding the distinction between user-level threads (ULTs) and kernel-level threads (KLTs), and how Go dynamically maps goroutines to kernel threads, developers can make informed choices about when and how to implement concurrency in their applications. Ultimately, mastering these concepts leads to building high-performance, scalable systems that efficiently utilize resources while delivering a seamless user experience.</p><p><strong>Reference</strong></p><ul><li>Geeksforgeeks: <a href="https://www.geeksforgeeks.org/thread-scheduling/">https://www.geeksforgeeks.org/thread-scheduling/</a></li><li>Brandon Wofford: <a href="https://bwoff.medium.com/the-comprehensive-guide-to-concurrency-in-golang-aaa99f8bccf6">https://bwoff.medium.com/the-comprehensive-guide-to-concurrency-in-golang-aaa99f8bccf6</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bdc1fceabcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>