<?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 Serine Daouk on Medium]]></title>
        <description><![CDATA[Stories by Serine Daouk on Medium]]></description>
        <link>https://medium.com/@serinemdaouk?source=rss-5137954bda1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xr1IxXvHla332mvWDYqcqw.png</url>
            <title>Stories by Serine Daouk on Medium</title>
            <link>https://medium.com/@serinemdaouk?source=rss-5137954bda1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:39:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@serinemdaouk/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[Cores, Threads, and Warps: The All-in-One Guide to How Processors Actually Work]]></title>
            <link>https://medium.com/@serinemdaouk/cores-threads-and-warps-the-all-in-one-guide-to-how-processors-actually-work-5e3117c6c058?source=rss-5137954bda1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3117c6c058</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Serine Daouk]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 09:57:16 GMT</pubDate>
            <atom:updated>2026-11-27T11:06:03.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding what your hardware does under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTZzdm7EIJnRAZnB" /><figcaption>Photo by <a href="https://unsplash.com/@ocollet?utm_source=medium&amp;utm_medium=referral">Olivier Collet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we’re going to dive into the hardware side of things. I’m more of a software-oriented person, but as I mature, I realise how important it is to understand how the underlying hardware works. It helps me write better software, and I’ve come to see that the two go hand in hand.</p><p>We’ll start with the CPU, move on to the GPU, then look at memory and how everything stays in sync. By the end, terms like SMT, SIMD, warps, blocks and VRAM should finally make sense.</p><p>So, let’s start!</p><h3>From a program to the CPU</h3><p>When we run any program on our computer, the operating system first creates the underlying <strong>process</strong> for it. That process then spawns one or more <strong>threads</strong> to actually execute the work needed for this program. These threads are sequences of instructions, ready to be executed on some data, and together they make up the work our program does.</p><p>The instructions in those threads are executed on the CPU by its <strong>cores</strong>.</p><p>A <strong>core</strong> is the physical hardware that contains the execution units (the parts that actually do the maths and logic) responsible for running these instructions.</p><p>A CPU can have one core or many.</p><p><em>Though these days, it’s rare to find a CPU with just one core, given how much work computers are expected to handle and how quickly they’re expected to deliver it.</em></p><h3>What a single core can run</h3><p>A core can run:</p><ul><li>One instruction from one thread.</li><li>Several instructions coming in from one thread, as long as they’re completely independent of each other (And this is called <strong>Instruction-Level Parallelism</strong>, or ILP).</li><li>Several instructions coming in from more than one thread (this is a special case, which requires the CPU to support <strong>Simultaneous Multithreading mode</strong>, or SMT).</li></ul><p>In short, SMT is a CPU design feature that lets a single core execute instructions from multiple threads at the same time.</p><p>This is where we introduce something called <strong><em>thread context</em></strong>.</p><p>Each thread has its own thread context, meaning its own registers (tiny, ultra-fast storage slots inside the core) and its current position in the program. <em>Basically the stuff that defines it.</em></p><p>A simple, non-SMT core can only follow one thread context at a time. It can still run several instructions at once, but only if they all come from that same thread.</p><p>An SMT-core, on the other hand, can keep track of several thread contexts at once, so it always knows which thread an instruction belongs to. That’s what allows it to run instructions coming in from more than one thread at the same time.</p><h3>When the CPU isn’t the right tool</h3><p>So far, all of this work has been happening on the CPU. But sometimes, part of our program’s work is better off running on the GPU instead.</p><p>This is usually <strong>work where the same operation needs to be applied to a huge amount of data</strong>. The GPU can operate on all of its simultaneously, faster and more efficiently than a CPU can.</p><p>When this happens, a CPU thread launches what’s called a <strong>GPU kernel</strong>.</p><p>A GPU kernel is basically a function that we give to the GPU, which it then applies to a large amount of data at once.</p><p>When a kernel is launched, the GPU creates a large number of logical threads, each applying that same function (the kernel) to its own piece of the data.</p><p>This follows the <strong>Single Instruction, Multiple Data</strong> (SIMD) idea, which on GPUs is often called SIMT, or <strong>Single Instruction, Multiple Threads</strong>.</p><p>And that’s the power of running operations on the GPU: <strong>the parallel execution of instructions</strong>.</p><p>On top of that, we get <strong>asynchronous execution</strong>.</p><p>When the CPU offloads a kernel to the GPU, it doesn’t wait for the GPU to finish before moving on, but instead, it carries on with other work and only waits when it actually needs the results.</p><p>That’s the nice thing about this, <em>and we’ll come back to it later in the article.</em></p><h3>What a GPU is made of</h3><p>Just like a CPU has cores, a GPU has <strong>Streaming Multiprocessors</strong> (SMs).</p><p>An SM has execution units, registers, scheduling hardware and shared memory, <em>very much like a core in a CPU</em>. The difference is that a GPU has many more of them, and each one is built to run a huge number of threads at once.</p><p>To better unpack this, let’s follow a kernel from the moment it’s launched.</p><p>All the threads created by one kernel launch form a <strong>grid</strong>.</p><p>The grid is split into <strong>blocks</strong>, and <strong>each block is a group of threads</strong>.</p><p>The GPU then <strong>assigns each block to an SM which runs it</strong>. An SM can host several blocks at the same time.</p><p>Inside a block, threads (similar to CPU-level threads) represent a sequence of instructions to be executed on some data. These threads are grouped into <strong>warps</strong>, where a warp is 32 threads (<em>on NVIDIA GPUs</em>).</p><p>So, from the hardware’s point of view, the order becomes:</p><p><strong>SM -&gt; Blocks -&gt; Warps -&gt; Threads.</strong></p><p>A block can’t be split across SMs. Once a block is assigned to an SM, all of its warps and the threads inside of them execute only on that SM. This is also what lets threads within the same block cooperate, since they share that SM’s shared memory and synchronize with each other.</p><h3>How warps keep the GPU busy</h3><p>Threads in the same warp typically execute the same instruction at the same time, each on a different piece of data.</p><p>Some instructions, like reading from memory, take a lonf time. Rather than sitting idle while a warp waits, the SM switches to another warp that’s ready to run. We want to avoid any idle time on the GPU, so it always tries to swap in a ready warp. This is called latency hiding: we keep the GPU busy and hide the parts that take longer.</p><h3>The full picture</h3><p>Putting it all together, the overall hierarchy becomes:</p><p>OS -&gt; CPU process -&gt; CPU thread -&gt; launches kernel -&gt; GPU grid -&gt; Blocks -&gt; Warps -&gt; GPU threads.</p><p>A CPU process can launch many GPU kernels, and multiple processes can share the same GPU.</p><h3>Memory Hierarchy</h3><p>So far, we’ve mainly talked about who does the actual work. But all of these threads need data to work on, and where that data lives makes a big difference to how fast things go.</p><p>The rule of thumb for hardware: <strong>The closer the memory is to the execution units, the faster it is, but also the smaller it is</strong>.</p><p>Both a CPU and a GPU have several layers of memory. I’ll list them ranked from the closest/fastest to the furthest/slowest.</p><p>For a CPU, we have:</p><ul><li>The <strong>registers</strong> inside each core</li><li>The <strong>L1</strong> and <strong>L2 caches</strong>, which each core usually has its own of</li><li>The <strong>L3 cache</strong>, shared between all cores</li><li>And finally the <strong>RAM</strong> (main memory), which sits outside the CPU.</li></ul><p>For a GPU, it’s sort of similar:</p><ul><li><strong>Registers</strong>: each thread gets its own set of registers, taken from a large pool on the SM.</li><li><strong>Shared memory: </strong>this is ‘fast’ memory on each SM. Each block running on that SM gets its own slice, and other blocks on the same SM can’t access it (to each their own). It’s built from the same physical memory as the SM’s <strong>L1 cache</strong>, which is why you’ll often see the two mentioned together.</li><li><strong>L2 cache</strong>: this one is shared across all SMs.</li><li><strong>Global memory</strong>, aka <strong>VRAM</strong>: the GPU’s main memory.</li></ul><p>Keep in mind that the CPU and GPU each have their own main memory (RAM and VRAM). Data usually has to be copied from RAM into VRAM before the GPU can work on it, and the results get copied back afterwards. <strong>That trip in itself is relatively slow</strong>, so we try to do it as little as possible.</p><h3>Don’t overdo it</h3><p>Registers are the fastest memory we have, and they’re where threads keep the intermediate data they’re working with. But the registers on an SM are a shared pool, and that has two important consequences:</p><p>(1) First each SM has a fixed number of registers, shared between all the threads running on it. The more registers each thread needs, the fewer threads, and so the fewer warps, can fit on the SM at once.</p><p>And fewer warps means fewer options to switch to while one is waiting on memory, so we lose some of that latency hiding. How full an SM is compared to its maximum is called occupancy.</p><p>(2) Second, when a kernel needs more intermediate data than its resgiters can hold, the extra load spills over into what’s called <strong><em>local memory</em></strong>. Despite the name, local memory isn’t close at all.</p><p>It’s private to each thread, but it physically lives in VRAM (with some help from the caches). This is called <strong><em>register spilling</em></strong>, and it can slow a kernel down noticeably because of the data transfer overhead caused by the spilling.</p><p>So keeping data close is great, but asking for too much of the fastest memory can also backfire.</p><p><em>Just, don’t overdo it.</em></p><h3>GPU execution and synchronization</h3><p>We’ve seen that the CPU and GPU work asynchronously: the CPU launches a kernel and carries on with other work. That’s great for performance, but it raises two important points:</p><p>How does the CPU know when the GPU is done? And how do threads that depend on each other’s work coordinate?</p><p>That’s where <em>synchronization</em> comes in.</p><h4>Between the CPU and GPU</h4><p>At some point, the CPU needs the GPU’s results. To get them it has to wait for the GPU to finish, i.e. <em>synchronize</em>.</p><p>In CUDA (that’s NVIDIA’s platform for programming GPUs), this is done with calls like cudaDeviceSynchronize().</p><p>Copying the results back from VRAM to RAM will also wait for the work before it to finishes. However, every time the CPU waits, it’s sitting idle, which takes away the benefit of working asynchronously.</p><p>So we only want to synchronize when we <em>actually need</em> the results.</p><p>To organize all this work, kernel launches and memory copies are all placed in queues called <strong>streams</strong>. Work in the same stream runs in order, one after the other. Work in different streams can overlap. For example, the GPU can be computing one chunk of data while the next chunk is still being copied over.</p><h4>Between blocks</h4><p>Inside a kernel, there’s no guaranteed order between blocks, Depending on how many SMs are free, some blocks might run at the same time and others one after the other. That’s why each block should be able to do its work on its own, without depending on other blocks.</p><h4>Inside a block</h4><p>Threads within the same block can synchronize using a barrier (__syncthreads() in CUDA). When a thread reaches the barrier, it waits there until every other thread in the block has reached it too.</p><p>An example of that would be: each thread loads a piece of data into shared memory, then they all hit the barrier, and only then does each thread read the pieces its neighbours loaded. Without the barrier, a thread might try to read a value before its neighbour has finished writing it.</p><h4>Inside a warp</h4><p>Since threads in a warp execute the same instruction at the same time, what happens when an if statement sends some threads one way and the rest the other way? The warp runs both paths one after the other, and the threads that didn&#39;t take the current path simply sit idle.</p><p>This is called <strong>warp divergence</strong>, and it means the warp takes as long as both paths combined. So on a GPU, it’s best when threads in the same warp follow the same path through the code.</p><h3>And that’s a warp folks! (get it?)</h3><p>This guide was definitely more of a generalized version to get you introduced into the underlying hardware of your computer and how your program use them.</p><p>You can definitely go much deeper into the different topics I touched upon and I highly recommend you do.</p><p>I’ll finish off by adding a quick Jargon cheat sheet to be used as a reference/index of all the important terms I mentioned in my article.</p><p><strong>Jargon cheat sheet</strong></p><ul><li><strong>Process:</strong> a running program, created by the operating system</li><li><strong>Thread:</strong> a sequence of instructions to be executed on some data</li><li><strong>Core:</strong> the physical hardware in a CPU that executes instructions</li><li><strong>ILP:</strong> a core running several independent instructions from the same thread at once</li><li><strong>SMT:</strong> a core running instructions from several threads at once</li><li><strong>Thread context:</strong> a thread’s registers and current position in the program</li><li><strong>SIMD / SIMT:</strong> one instruction applied to lots of data / by lots of threads at once</li><li><strong>Kernel:</strong> a function the CPU hands to the GPU to apply to a large amount of data</li><li><strong>SM:</strong> a Streaming Multiprocessor, the GPU’s equivalent of a CPU core</li><li><strong>Grid:</strong> all the threads created by one kernel launch</li><li><strong>Block:</strong> a group of threads within a grid, assigned to a single SM</li><li><strong>Warp:</strong> a group of 32 threads that execute the same instruction together</li><li><strong>Latency hiding:</strong> switching to a ready warp while another waits on memory</li><li><strong>Shared memory:</strong> fast memory on an SM, private to each block</li><li><strong>VRAM / global memory:</strong> the GPU’s main memory</li><li><strong>Memory coalescing:</strong> combining the memory reads of neighbouring threads into fewer accesses</li><li><strong>Register spilling:</strong> extra data overflowing from registers into slow local memory</li><li><strong>Stream:</strong> a queue of GPU work that runs in order</li><li><strong>Barrier:</strong> a point where all threads in a block wait for each other</li><li><strong>Warp divergence:</strong> threads in one warp taking different paths, which slows the warp down</li></ul><p>Thank you for taking the time to read this and I hope it helped you in some way!</p><p>See you in another dive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3117c6c058" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Did My Docker Images Double in Size? A Trip Down to the Linux Kernel]]></title>
            <link>https://medium.com/@serinemdaouk/why-did-my-docker-images-double-in-size-a-trip-down-to-the-linux-kernel-f46532585b75?source=rss-5137954bda1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f46532585b75</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Serine Daouk]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 19:03:31 GMT</pubDate>
            <atom:updated>2026-11-05T19:03:31.881Z</atom:updated>
            <content:encoded><![CDATA[<p>How a disk-usage mystery led me through kernels, namespaces and Docker’s switch to the containerd image store 🐳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfSc2TW7fv3d5lFk" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This all started when I was investigating why my container images on my computer starting taking up more disk usage than what their actual content size was, almost double (which never happened before until recently in my experience).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*aDQPVENSTGZ9JB0QpeW6vQ.png" /><figcaption>Actual screenshot from my laptop</figcaption></figure><p>While looking into it, this investigation led me all the way down to the operating system (OS) level to try and understand what prompted this new change in Docker’s storage management.</p><p>In this deep dive, I’m going to hold your hand while we learn a bit of everything from OS, what are kernels, docker itself and finally why this doubling in disk size was happening in the first place.</p><blockquote><strong>Side note:</strong> I think, as software engineers, we shouldn’t be afraid to reach into the deep low-level stuff that make up the tools and systems we use in our day-to-day. As taunting as it sounds to get our hands dirty in the unknown, doing so will teach us so much more about software and computers.</blockquote><p><strong>So now, let’s dig in!</strong></p><h4>The base of it all: The operating system</h4><p>The operating system is the base software that manages your computer’s hardware and lets every other program run on it.</p><p>Its core component is called the “kernel”, a program that lives on disk just like any other program. It’s like the heart of your OS.</p><p>When we turn on our computers, the CPU (Central Processing Unit) wakes up already set to its most privileged mode, so that the first programs that run at startup have direct, full access to the hardware. This privileged mode, called “kernel mode”, later gets switched down to a less-privileged mode called “user mode”, to better protect our hardware.</p><blockquote>The “kernel” program that our CPU will run later on is not the same as the privileged “kernel mode” our CPU is set to. These are two different concepts that happen to have the same name (<em>I know, it can be confusing</em>).</blockquote><p>The first thing a CPU is wired to do is run a program stored at a specific address on a flash chip on the motherboard, called the <strong>firmware</strong> (UEFI/BIOS). The firmware checks and initializes (i.e. wakes up) the hardware components of our computer.</p><p>After it’s done, the second program gets fetched from disk to run: the <strong>bootloader</strong>, whose only job is to load the kernel program from disk into memory so the CPU can immediately start executing it.</p><p>Technically speaking, the kernel <em>is</em> the first part of the operating system to run, but not the first software: the firmware and the bootloader run before it.</p><p>Now, when the CPU starts running the kernel program from memory, the kernel uses the CPU’s privileged state to set up some rules before allowing any other program to run on our computer.</p><p>These rules include:</p><ul><li>Marking its own place in memory as “supervisor-only” (Kind of like it was saying “<em>That’s my spot</em>” in memory).</li><li>Setting up the entry points through which the CPU can jump back into “kernel”/privileged mode while it’s in “user” mode: system calls made by regular programs, and interrupts triggered by hardware, like timers.</li></ul><p>And other important rules that dictate how the hardware and the operating system will interact with one another to successfully run our programs.</p><p>One of the other important things the kernel sets up at this stage is the <strong>“initial namespaces”</strong>.</p><h4>What are these namespaces?</h4><p>While the kernel is still running in the CPU’s kernel mode, it also builds its own internal bookkeeping: lists of processes, the memory map, the hardware device drivers, and the system state that programs will ask about, with questions like:</p><ul><li>What is the machine’s hostname?</li><li>What filesystems are mounted, and where?</li><li>What network interfaces, IP addresses and routes exist?</li><li>Which process IDs are in use?</li></ul><p>The kernel doesn’t keep this system state in loose global variables; it groups it into objects called namespaces, one per category.</p><p>[Namespace = ns]</p><ul><li>The UTS ns stores -&gt; hostname = “my-laptop”</li><li>The Mount ns stores -&gt; / = disk partition 2, /boot = partition 1, /proc, /sys</li><li>The Network ns stores -&gt; network interfaces, IP addresses, routes</li></ul><p>And there are a few other namespaces like these that the kernel prepares at startup.</p><p>This is kind of like putting the system state “answers” to these system state “questions” in their respective boxes (that kernel sure loves to organize things).</p><p>Finally, when the kernel is done and everything is organized, the CPU switches to “user mode” to run regular programs. Once these programs start running on our machine, each one gets a set of pointers, one for each type of namespace, pointing to the namespaces the kernel created. And whenever a process starts another one, the child copies its parent’s pointers.</p><p>So all of these newly created processes point to the same namespaces, with the same system state stored in each, effectively seeing the same data.</p><p><em>So where does containerization come into play in all that?</em></p><h4>Docker!</h4><p>As a quick refresher: Docker is a containerization tool that allows us to package software into images: movable bundles that can run anywhere there’s a Linux kernel, since they pack everything the software needs, from its libraries to its dependencies and everything in between, except for the Linux kernel itself, which every container shares with the host machine it’s running on.</p><p>A container is simply a running instance of an image.</p><p>So when we run docker run …, the request passes down a chain of different programs until it reaches a particular one called runc: a program that, when invoked, asks the kernel for a whole new set of namespaces.<br>So for most of the namespaces the kernel created at startup, runc and Docker ask for a brand-new one of the same type, but this time with different system state values that they’ll fill in using a mix of predefined values and user-provided values.</p><p>The kernel essentially provides them with the same kinds of boxes it filled at startup, some empty and some pre-filled with a copy of the host’s values, for Docker to fill or overwrite.</p><p>Namespaces control what a process sees, and by giving a container its own set, we’re limiting the container’s field of vision to only itself, making it think it’s the only thing running on our device.</p><p>What namespaces don’t control is how much hardware the container can use: the container still believes it has all the CPU and memory available, and that’s where a second kernel feature, cgroups (control groups), steps in to limit it to a certain chunk.</p><blockquote>We won’t get into those now, but they’re worth the lookup.</blockquote><p>One important namespace that gets set up during this containerization process is the mount namespace, specifically its root filesystem: i.e. the filesystem the Docker container can see.</p><p>A filesystem is simply how files and folders are organized on storage: the tree that starts at / and branches into /bin, /etc, /usr and so on.</p><p>A Docker image is made of layers, where each layer is the set of files added or changed by one step of the image’s build (one for the base OS, one for installed libraries, one for your app’s code, etc.). Layers are stored in a registry (like Docker Hub) as compressed .tar.gz archives because they’re smaller to download, but a program can’t run from inside a compressed archive, so Docker unpacks each layer back into real files and folders on disk when we pull the image to our computer.</p><p>Then the kernel’s overlayfs comes in (<em>back at it with that handy kernel program</em>): it’s a Linux feature that stacks several folders on top of each other and presents them as one merged filesystem.</p><p>Once that merged filesystem is ready, runc mounts it inside the container’s new mount namespace and makes it the container’s /.</p><p>Docker used to manage all of this with its classic image store and its overlay2 storage driver: a component inside the Docker daemon (dockerd, the brains of Docker) that saved each unpacked layer as a folder under /var/lib/docker/overlay2 and asked the kernel’s overlayfs to stack them. When downloading layers, it unpacked them and deleted the .tar.gz part, so we were left with just our unpacked image layers.</p><p>Docker has since switched to the containerd image store, handing image management over to containerd, the runtime Docker originally built and that Kubernetes now uses as its standard. It was introduced as an experimental option in 2022, became the default for new Docker Desktop installs in 2024, and became the default for new Docker Engine installs in late 2025. The goal behind this switch was to unify Docker with the rest of the container ecosystem.</p><p>But it works differently: after downloading and unpacking the compressed layers, it keeps both, because the compressed files carry the image’s identity, which is used to verify, sign and push the image unchanged. It still uses the same kernel overlayfs underneath; it only changed how images are stored on our computer. That’s why the same image now takes up roughly double the disk space.</p><h4>Linux? What are you doing here?</h4><p>Now, you might have noticed that I mentioned Docker packages everything except the Linux kernel, which it needs to run (as we’ve seen throughout this article).</p><p>The Linux kernel that most of you have probably heard about is the same program we introduced at the start of the article, and its name is Linux. Yup, that’s the famous Linux kernel. Strictly speaking, “Linux” is just the kernel; systems like Ubuntu or Debian are full operating systems built around it. And since containerization depends so much on the Linux kernel and its internal functionality, Linux containers can only run on top of a Linux kernel.</p><p>That’s why on Mac or Windows computers, which use a completely different kernel program of their own (XNU on macOS, the NT kernel on Windows), installing Docker Desktop means it runs a small Linux Virtual Machine (VM) in the background. The VM uses the CPU’s built-in virtualization support to boot a real Linux kernel on virtual hardware, and all of our containers run inside it, sharing that one kernel. That’s also a good thing to keep in mind.</p><h4>Closing thoughts</h4><p>I hope you enjoyed this deep dive as much as I enjoyed discovering all of this.</p><p>See you in the next plunge!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f46532585b75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Numba Makes Python Faster: From Bytecode to Machine Code]]></title>
            <link>https://medium.com/@serinemdaouk/how-numba-makes-python-faster-from-bytecode-to-machine-code-bd26da288d93?source=rss-5137954bda1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd26da288d93</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Serine Daouk]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 17:34:42 GMT</pubDate>
            <atom:updated>2026-10-25T17:34:42.956Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding how CPython compiles and interprets Python code and how we can supercharge it with Numba.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xYxNKro6PL9JIlg5" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’ve been around Python for long enough you already know that it’s not the fastest language out there, nor the most efficient one.</p><p>The most widely used implementation of Python is actually written mainly using the C language under the hood, and the “official” Python distribution (i.e. the Python we download from their official website) uses this implementation, hence why you might hear some people call it CPython.</p><p>Let’s dive a bit more into it.</p><h4>Understanding the C under the snake</h4><p>For anyone unfamiliar with C, whenever someone writes C code (so a <strong>xyz.c</strong> file) they’ll typically have to first <strong>compile</strong> it and then they’ll be able to actually execute it.</p><p>C is a compiled language, meaning its source code is typically compiled into machine code (the 0s and 1s) before it can be executed.</p><p>Here’s an example of C code: <strong>main.c</strong></p><pre>#include &lt;stdio.h&gt;<br><br>int main(){<br>    printf(&quot;Hello, World!\n&quot;);<br>    return 0;<br>}</pre><p>This script can then be compiled using one of the many C compiler tools out there, we’ll use <strong>gcc</strong> for our example here:</p><pre>gcc main.c -o main</pre><p>This command takes our main.c file, compiles it, and generates an executable called main (or main.exe for Windows).</p><p>Then we can run:</p><pre>./main</pre><p>Which will finally execute our code and output:</p><pre>Hello, World!</pre><p>The same applies to CPython. Its C source code is compiled into machine code, producing an executable.</p><p>So when you download and install Python from the official website, you’re downloading an <strong>already-compiled version of CPython</strong>, ready to execute your Python scripts on your machine.</p><h4>Back to the snake</h4><p>Now say we have our Python file ready to be run, <strong>main.py</strong>:</p><pre>def main():<br>    print(&quot;Hello there.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>We’ve already mentioned that the Python we download on our machine is the already compiled CPython, so when we want to use it to run our scripts it’s already in an ‘executable’ format ready to do so.</p><p>What CPython will do is take our Python code and compile it into a format called <strong>Python bytecode</strong>.</p><p>Bytecode is a set of lower-level instructions that CPython understands, but that the CPU cannot directly execute.</p><p>The compilation produces an output similar to the following (depending on the Python version, because the bytecode might differ between one python version and another):</p><pre>RESUME<br>LOAD_GLOBAL      print<br>LOAD_CONST       &#39;Hello there.&#39;<br>CALL             1<br>POP_TOP<br>LOAD_CONST       None<br>RETURN_VALUE</pre><p>These are the bytecode instructions CPython generated from our Python function.</p><p>This bytecode is then picked up by the <strong>CPython interpreter</strong>, which fetches and decodes each instruction, identifies the corresponding machine code that implements it, and executes it on the CPU before moving on to the next instruction.</p><p>Remember that CPython itself was already compiled from C into machine code before we even downloaded it. This means that the corresponding machine code for our Python’s bytecode instructions is already packaged within the CPython executable. There’s no need to translate each bytecode instruction into new machine code at runtime, since CPython already has the native implementations ready to execute.</p><pre>                        Python source code<br>                                ↓<br>                        CPython bytecode compiler<br>                                ↓<br>                        Python bytecode<br>                                ↓<br>                        CPython interpreter<br>                                ↓<br>                        Existing native machine code<br>                                ↓<br>                               CPU</pre><h4>Bring out the Numba</h4><p>Now you might be wondering: “This all sounds super great so why do I need anything to improve on this, seems like a pretty good process.” And it is, but don’t let the cute-looking snake fool you.</p><p>Python is great and it’s not as bad as everyone says it is, but it could definitely benefit from a <em>boost</em> to help speed up and optimize its work.</p><p><strong>Numba</strong> is a Python library that allows us to decorate certain functions in our code so that, instead of having CPython’s default interpreter execute their bytecode instruction by instruction using its already-compiled machine code, Numba takes that same bytecode and generates new machine code specifically for those functions.</p><p>The difference is that CPython’s machine code is designed to interpret Python instructions, while Numba’s generated machine code is designed to execute the function’s operations directly, without having to go through the interpreter for every instruction. This removes much of the overhead involved in interpreting Python bytecode, which can significantly speed up numerical computations and loops.</p><p>It does this using a <strong>Just-In-Time (JIT) compiler</strong>, which generates machine code at runtime, usually when we first call the decorated function. This means that instead of repeatedly going through CPython’s interpreter for every instruction inside that function, we can execute the newly compiled machine code directly.</p><p>So compared to CPython’s interpreter, which identifies bytecode instructions and executes their corresponding already-compiled machine code, Numba takes those bytecode instructions and compiles them into new machine code at runtime, specifically optimized for the decorated function.</p><p>Let’s take a simple example to see this in action:</p><pre>import numpy as np<br>from numba import njit<br>import timeit<br><br>def calculate(arr):<br>    total = 0.0<br>    for i in range(len(arr)):<br>        total += arr[i] * arr[i]<br>    return total<br><br>@njit<br>def calculate_numba(arr):<br>    total = 0.0<br>    for i in range(len(arr)):<br>        total += arr[i] * arr[i]<br>    return total<br><br>arr = np.arange(1_000_000, dtype=np.float64)<br><br># First call triggers Numba compilation<br>calculate_numba(arr)<br><br># Measure normal Python<br>python_time = timeit.timeit(<br>    lambda: calculate(arr),<br>    number=10<br>) / 10<br><br># Measure compiled Numba<br>numba_time = timeit.timeit(<br>    lambda: calculate_numba(arr),<br>    number=100<br>) / 100<br><br>print(f&quot;Python: {python_time:.8f} seconds&quot;)<br>print(f&quot;Numba:  {numba_time:.8f} seconds&quot;)<br>print(f&quot;Speedup: {python_time / numba_time:.1f}x&quot;)</pre><p>Both functions perform the same calculation, but there’s one important difference: the second function uses the @njitdecorator.</p><p>To generate this machine code, Numba uses something called <strong>LLVM</strong>, which is a <em>compiler infrastructure</em> designed to optimize code and translate it into machine code that can run on a CPU.</p><p>Numba first takes our CPython bytecode, processes it into its own intermediate representation (IR), figures out the types involved, and then converts it into a format LLVM understands, called LLVM IR (Intermediate Representation).</p><p>LLVM then takes care of optimizing that code and generating the actual machine code for our CPU.</p><p>So instead of Numba having to build its own machine code generator from scratch, it can rely on LLVM to handle that part of the compilation process.</p><pre>                         Python bytecode<br>                                ↓<br>                          Numba compiler<br>                                ↓<br>                            Numba IR<br>                                ↓<br>                             LLVM IR<br>                                ↓<br>                              LLVM<br>                                ↓<br>                      New native machine code<br>                                ↓<br>                               CPU</pre><p>And here are the results:</p><pre>Python: 0.09020482 seconds<br>Numba:  0.00049358 seconds<br>Speedup: 182.8x</pre><h4>Closing thoughts</h4><p>Now, this doesn’t mean Numba will magically make every Python function faster. It works particularly well with numerical computations, loops, and supported NumPy operations, but not every Python feature can be compiled this way.</p><p>There’s also an initial compilation cost when a decorated function is first called, so for functions that only run once or perform very little work, Numba might not provide much of a benefit.</p><p>But when you’re dealing with computationally expensive operations that run repeatedly, Numba can make a significant difference.</p><p><em>Thanks a lot for reading. Follow for more articles.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd26da288d93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining Basic Machine Learning algorithms to your neighbors]]></title>
            <link>https://medium.com/@serinemdaouk/explaining-machine-learning-algorithms-to-your-neighbors-pt-1-d0e7f29dc241?source=rss-5137954bda1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e7f29dc241</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Serine Daouk]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 03:27:11 GMT</pubDate>
            <atom:updated>2026-09-18T07:31:23.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0_6sktgdyp54dp1a" /><figcaption>Photo by <a href="https://unsplash.com/@kimberlyfarmer?utm_source=medium&amp;utm_medium=referral">Kimberly Farmer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a machine learning engineer, I don’t like to find myself in situations where I need to explain how an ML algorithm works without sounding too standoff-ish by using fancy mathematical terms or having the other person feel uninterested or confused by what I’m saying.</p><p>I do, however, still like to provide some mathematical clarity when needed without omitting the core parts of these algorithms.</p><p>Which is why I decided to write an <em>ExplainLikeIm5 </em>type of definitions to some ML algorithms.</p><p>These explanations can take two minutes to explain to your parents, partner, neighbors, dog or just anyone who’s curious on how ML algorithms work without forcing them to take an <em>intro to ML</em> prerequisite course.</p><h3>Let’s get <strong>started</strong></h3><p>In this article, I’ll focus on <strong>supervised algorithms</strong> and I’ll go into unsupervised and other types of machine learning models in the upcoming parts of this series.</p><p><strong>Quick revision before we start:</strong></p><p>Machine learning is a branch of AI where computers learn from data to make predictions or decisions without being explicitly programmed.</p><p>We use algorithms to build models from input data and use these models to perform tasks like classification, regression, clustering, and more.</p><p><strong>Supervied algorithms</strong> are the ones that get trained on both the data and its label, and are divided into either <em>regression</em> and <em>classification</em> algorithms.</p><p><em>Classification algorithms</em> return a fixed (discrete) prediction that indicates a state or a category (e.g. 0 or 1 , yes or no, dog or cat, etc).</p><p><em>Regression algorithms</em> return a (continuous) prediction that indicates some value like a price or an estimate (e.g. 1.487, -42.8, 748.144, etc).</p><blockquote><em>Now, let’s start !</em></blockquote><h3><strong>(1) Linear Regression</strong>:</h3><p>Linear regression is an algorithm that helps us find the most accurate (best) straight line that through a set of data points.</p><p>(Small condition: When looking for such a line, the data needs to have a linear pattern in it. Meaning we can roughly draw a straigh line through that data in order to capture its essence.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHXMv9FY5OlQ8yjq9eFe8A.png" /><figcaption>Image made by the author</figcaption></figure><p>Our goal is to find a line that best represents the <em>linear </em>relationship between the points, in a way that minimizes the line’s distance from each point.</p><p>The line can then be used as a basis for future prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzQgCSmckMceBS2p5iUlQg.png" /><figcaption>Image made by author</figcaption></figure><p>This line is represented with the typical line equation: y = mx + b</p><ul><li><strong>y:</strong> is the value we’re trying to predict.</li><li><strong>x:</strong> is the input value.</li><li><strong>m:</strong> is the slope of the line (it shows the steepness and the direction of the line).</li><li><strong>b</strong>: The y-intercept which is the value of y when x = 0.</li></ul><p>All of these parameters allow us to draw the line.</p><p>To minimizes the distance from the line to each point we calculate something called the “sum of squared errors” (SSE) which gives us a value of “<em>how far off our line is from the points”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*ZoKq8l5gXKYztaUCKMIC5g.png" /><figcaption>Image made by author</figcaption></figure><p>By adjusting and playing around with the <strong>m</strong> and <strong>b</strong> values of our equation we can minimize the SSE for each point in the most optimal to get the best-fitting line.</p><p>Once we’ve drawn out our line, we can simply plug in any new input value into <strong>x</strong> and solve for <strong>y</strong> to get the prediction for this input.</p><p>To summarize:</p><blockquote><strong>Linear Regression</strong> is an algorithm best suited for data that has a linear pattern. It allows us to draw a line that best fits and describes this data so that it can be used as a basis for future preditcions. It finds such a line by looking for one that has the smallest minimal distance from all points.</blockquote><h3><strong>(2) Logistic Regression:</strong></h3><p>Logistic regression is an algorithm that predicts if something belongs to one group or another (like yes or no, 0 or 1).</p><p>The algorithm first look at clues or features about the data we’re working with (let’s call them x1, x2,…​) and assigns an importance or weight to each feature (x1 → w1, x2 → w2, …).</p><p>It then multiplies each feature by its weight and adds them all up along with a bias term <strong>b</strong>:</p><blockquote><em>z = (w1 . x1) + (w2 . x2) + … + b</em></blockquote><p>(The <em>b </em>term accounts for some baseline clue about our data in the case where the other clues (x1, x2, …) alone don’t provide all the information needed. )</p><p>Once this weighted sum is generated, we use a special function called the <em>sigmoid</em> <em>function (σ)</em> to turn this resulting value (z) into a probability. This function takes any number and squashes it between 0 and 1.</p><p>Finally, we can classify the result based on whether the number we get out of the sigmoid function is greater or less than 0.5.</p><ul><li>If σ(z) &gt; 0.5 we classify our input as class 1</li><li>If σ(z) &lt; 0.5 we classify our input as class 0</li></ul><p>To summarize:</p><blockquote><strong>Logistic regression </strong>is an algorithm for placing an input value in one group or another. It starts by calculating the weighted sum of the data’s feature values + some bias term. Then it passes this resulting value to a sigmoid function and finally checks if it’s above or below the 0,5 threshold to know in which group to place that input in.</blockquote><h3><strong>(3) Decision Trees:</strong></h3><p>A decision tree is an algorithm that behaves like a flowchart. It helps the computer make decisions based on a series of questions.</p><p>It starts with a question at the top and branches out based on the answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtjWgLRKHGpWPnmu9tQIug.png" /><figcaption>Image made by author</figcaption></figure><p>The algorithm generates the question to ask from the features of the data it’s working with; in our case our features would be: <strong>sunny, cloudy, windy</strong> with values indicating the value of these conditions for a specific day.</p><p>The algorithm then chooses the ordering of the questions to ask based on how well they split the data into pure groups (a measure of purity).</p><p><em>(An example of a pure group would be one where all the samples checked for a particular question like “Is it sunny” with all Yes or all No. The more diverse the samples for a given question the less pure it’s counted.)</em></p><p>For classification (deciding categories), it uses measures like Gini impurity or entropy to see how mixed the groups are. A lower value means a purer group.</p><p>For regression (predicting numbers), it uses variance to see how close the numbers are within each group. A lower variance means the numbers are more similar.</p><p>At each step, the tree evaluates all possible questions and picks the one that best splits the data into the purest groups.</p><p>The tree keeps branching by asking the best questions until it reaches the final decisions, which are easy to follow and understand.</p><p>Once the tree is built, it’s easy for us to pass in a new input with it’s feature values and follow along to determine the final value for that input.</p><p><em>To summarize</em></p><blockquote><strong>Decision Trees</strong> are a type of machine learning model that make decisions by splitting data into branches based on features. At each branch, the tree asks a question to split the data into more pure groups. This process continues until a final decision is reached, making it easy to visualize and understand how the model makes predictions.</blockquote><h3><strong>(4) Random Forest:</strong></h3><p>This algorithm is basically a collection of many decision trees, and each tree makes its own prediction.</p><p>Each tree is trained on a random sample/subset of the data.</p><p>Then, the forest combines these predictions to make a final decision. The final decision is made by a majority vote if it was classifying a data sample (deciding categories), or performs averaging if it was performing a regression task (predicting a number) for a data sample.</p><p>Generally, Random Forest is said to be a more robust algorithm because it’s less likely to make a wrong decision because it doesn’t rely on just one tree.</p><p>Even if some trees are wrong, the majority can still make the correct decision.</p><p><em>To summarize</em></p><blockquote><strong>Random Forest</strong> is a method that builds multiple decision trees and combines their predictions to improve prediction accuracy. The final prediction is made by averaging the predictions of all the trees (for regression) or taking the majority vote (for classification).</blockquote><h3><strong>(5) Support Vector Machine (SVM):</strong></h3><p>SVM is an algorithm that also draws the best-fit line, but it does so in order to seperate the data into distinctif groups. Fundementally, it works best when separating data points into <strong>two</strong> respective groups but there are way to tweak it to work with more than just 2.</p><p>The main advantage here is that the line doesn’t have to be straight, we can draw out a curve, plane or hyperplane.</p><p>The dimensionality of our “separator” depends on the number of features our data has. So, if we have <em>n </em>features, the data points are represented in an <em>n</em>-dimensional space.</p><p>Basically we’re answering the question “<em>What is the appropriate geometric form needed for this data in order to properly classify it into distinctif groups</em>”.</p><p>SVM finds the separator that best separates the classes with the <strong>maximum margin</strong>, ensuring clear and distinct classification.</p><p>For example, in the figure below, the two closest elements from each class have a little gold triangle next to them. These closes points are referred to as <em>support vectors</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*aTj7nUhCwSmQpB-D8fSv5w.png" /><figcaption>Image made by author</figcaption></figure><p>SVM will try to maximize the margin, i.e. <em>the distance between these support vectors</em>, to ensure proper distinction and separation of the data points from each group.</p><p>It will then draw the separator between those two lines.</p><p>The good thing about SVM as well is that it can work with non-linear data as well through a method called <strong>The Kernel Trick</strong>. This allows it to map (not transform) the non-linear data to a higher dimensionality where it becomes linear and can be separated by a separator much easily then.</p><p><em>To summarize</em></p><blockquote><strong>SVM</strong> is an algorithm that separates data points into different groups by maximizing the margin between the closest points from the different groups.</blockquote><h3><strong>(6) K-Nearest-Neighbors (KNN):</strong></h3><blockquote><strong>KNN</strong> is an algorithm that can classify a new data point based on who its nearest neighbors are.</blockquote><p>It looks at the “k” most closer neighbors that are already categorized and then assigns the new data point to the category that is most common among these neighbors.</p><p>For example in the figure below, looking at the closest 3 neighbors (k=3) we can see that the new data point (white) has among its closest neighbours 2 reds and 1 blue, meaning KNN will classify it as a red point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAjXKmIdjXWDfFJ738syWg.png" /><figcaption>Image made by author</figcaption></figure><p>There are several ways to determine which k value to use, it’s a <em>hyperparameter</em>, i.e. a characteristic of the algorithm that we can tweak and test with.</p><h3><strong>(7) Naive Bayes:</strong></h3><p>The Naive Bayes algorithm classifies a data point as belonging to one class or another by calculating the probability that this data point belongs to each category and then choosing the category with the highest probability.</p><p>One of its key features when performing this calculations is that it assumes that all features are independent of each other, which is why it’s called <strong><em>naive</em></strong>; meaning no features affects the other when taking into account the different factors of whether the points belongs to a certain class or not.</p><p>It relies on a mathematical equation called “<strong>Bayes’ Theorem</strong>” to calcuate these probabilities.</p><p>So given two events occurring, this is how we would express Bayes:</p><blockquote>P(A|B)= [P(B|A) . P(A)] / P(B)​</blockquote><p>Where:</p><ul><li>P(A|B) is the probability of event A occurring given that event B is true.</li><li>P(B|A) is the probability of event B occurring given that event A is true.</li><li>P(A) is the probability of event A occurring.</li><li>P(B) is the probability of event B occurring.</li></ul><p>It looks at the probability that the input data belongs to each class (A or B) based on its features and then compares which one has the highest probability in order to classifiy that input. For example, if we had 2 features in our data:</p><p><strong>P(A| feature_1, feature_2)</strong> Vs <strong>P(B| feature_1, feature_2)</strong></p><p><em>To summarize:</em></p><blockquote>The <strong>Naive Bayes</strong> algorithm classifies data points by calculating the probability that a point belongs to each class with respect to the given features using Bayes’ Theorem and selecting the class with the highest probability. It assumes that all features are independent, which simplifies the calculations.</blockquote><h3><strong>(8) Gradient Boosting:</strong></h3><p>The Gradient Boosting algorithm gathers up a bunch of models where each new model focuses on correcting the errors made by the previous models, gradually improving the accuracy of the predictions.</p><p>It relies on an important concept called “Boosting” which means that each model will be trained on a sample of the dataset, with the possibility of the same samples being used b y more than one model during their training.</p><p>It’s like a team of experts working together to make a decision. Each expert (or model) learns from the mistakes of the previous ones to improve the overall prediction.</p><p>This way, the combined models become very good at making accurate predictions.</p><p><em>To summarize</em></p><blockquote><strong>Gradient Boosting</strong> is a machine learning technique that builds a series of models, where each new model focuses on correcting the errors made by the previous models. This process gradually improves the overall accuracy of predictions and generates a strong predictor.</blockquote><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>And that’s all folks, I hope these explanations were clear and simple enough to help you share your knowledge about machine learning to almost everyone.</p><p>Please let me know your thoughts and stay tunned for <strong>Part.2</strong> of this series where I dive into <em>unsupervised algorithms</em>.</p><p>Thank you all !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e7f29dc241" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallelism, Concurrency, Multithreading, Multiprocessing, and all that jargon !]]></title>
            <link>https://medium.com/@serinemdaouk/parallelism-concurrency-multithreading-multiprocessing-and-all-that-jargon-a9c97ab11b7d?source=rss-5137954bda1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9c97ab11b7d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Serine Daouk]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 20:33:11 GMT</pubDate>
            <atom:updated>2023-02-02T14:22:04.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ooBHS5Tz77YT-RtL" /><figcaption>Photo by <a href="https://unsplash.com/es/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The goal of this article is to make sure you understand the above-mentioned concepts and more through clear and simple definitions.</p><p>We’ll start by defining the building blocks, then we’ll look into how these building blocks relate with each other to deliver different levels of performance.</p><h3>I. The building blocks</h3><h4>1. Threads &amp; Processes</h4><p>A <strong>program</strong> is a set of instructions, and its associated data, that reside in the computer’s storage (a.k.a disk). You can think of it as an app in its executable format (.exe) or even as a java or python file (.java or .py).</p><p>When you want to run a program, this program gets loaded from the computer’s disk, where it is saved, into memory (RAM) where it is now called <strong><em>a process. </em></strong>Formally speaking, a <strong><em>process</em></strong> <strong><em>is</em></strong> <em>a running instance of a program.</em></p><blockquote>In other words, a process is a program being executed.</blockquote><p>A <strong><em>thread </em></strong>is a small set of instructions designed to be scheduled and executed. It’s also referred to as <em>the smallest unit of execution within a process</em>. For example, you can think of a thread as a worker inside a process that picks up one or several instructions from the processes’ total instructions and then goes and waits in line for its turn to get them executed.</p><p>Another example is to consider several supermarket customers carrying one or more items, that they picked up from the supermarket shelves, inside their baskets and each waiting for their turn to checkout. In this context, the supermarket represents the process, the items represent the instructions in the process &amp; the customers are the threads.</p><p>A process always has at least one thread (called its main thread), but most often a process has multiple threads (workers) that carry out the different instructions that need to be executed.</p><p>Processes don’t share or communicate any resources with each other. For example, if you load the paint app on your computer and run a python code at the same time, they’re not going to interfere with each other. <strong><em>They are separate running processes, each with its own threads.</em></strong></p><p>However, threads <em>inside</em> one process can share the resources and data of the process they belong to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*xCWjrj5A_YAnob0Bbor3Hg.png" /><figcaption>Figure made by the author.</figcaption></figure><h4>2. CPU, cores, and the whole gang</h4><p>The <strong>CPU</strong> is the literal brain of a computer and it stands for<em> Central Processing Unit</em>. It does all the reading, processing, execution, etc.</p><p>In some machines, we might have several <em>independent</em> central processing units (CPUs) combined under one single component. In such a case, these independent CPUs are now called <strong>cores </strong>and the one single component which they are grouped under is known as a<strong> multi-core processor. </strong>A single CPU can also be referred to as a <strong>single-core processor.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*COy3KdAUEUV9XNiEbKePZQ.png" /><figcaption>Figure made by the author.</figcaption></figure><p>As we’ve mentioned earlier, when we want to execute a program it gets loaded into memory where it becomes known as a process. This process is made up of threads which are small sets of instructions that will be passed to a processor to be executed.</p><p>A processor can only handle executing one task at a time, i.e one thread at a time. So when a process needs to be executed, its threads bundle up, each holding some of its instructions all waiting to get executed one at a time by the processor.</p><p>Going back to our supermarket example, this would be analogous to a bunch of kids each holding a basket containing some of their mom’s groceries for the cashier to check them out. The cashier (i.e our processor) can check out one item at a time, while each kid waits for their turn to get their basket’s objects checked out.</p><p>Now our modern computers work super fast, meaning they can execute around 100 million instructions per second. This allows them to execute and switch between threads from several running processes at lightning speed without you even noticing.</p><p>So our cashier can check out one item from one kid’s basket and then one from another kid’s basket all at lightning speed to the point where you’d think they’re doing it all at the same time.</p><p>This is why, for example, you can keep moving your mouse while some youtube video is playing in the background all while your emails are being sent out. Your computer’s fast processing capabilities give you the illusion that it’s multitasking (i.e executing a lot of threads from several processes at the same time) when actually if we look closely enough, it’s just running one instruction at a time.</p><p><strong><em>So what’s the point of having multiple cores?</em></strong></p><p>What I just talked about describes a single-core processor setup where we just have one processor that can execute one instruction at a time. Imagine we’re now working with a multi-core processor, so now threads can be executed by any of the available cores, thus allowing for <strong><em>simultaneous thread execution.</em></strong></p><p>A single-core processor might reach a point where it’s <em>overwhelmed </em>by the number of programs (processes) you’re trying to run and you’ll notice your computer lagging or slowing down at a certain point.</p><p>A multi-core processor is more than ready to handle all the programs you wish to run at the same time while keeping your user experience as smooth as possible.</p><h4>3. Physical cores Vs Logical cores</h4><p>Remember how I said up there that “<em>a processor can only execute one task at a time</em>”, well these types of processors are called <strong>single-thread processors </strong>and that’s how most computer processors started.</p><p>Nowadays, processors in a computer can run more than one thread at a time. This phenomenon emerged as something called<strong> Hyper-threading</strong> where each physical core can run two threads.</p><p>Back to our supermarket example, hyper-threading could be thought of as the cashier checking out items from two different customers on two different conveyor belts at the same time instead of working on just one conveyor belt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WVDv8seuIAhyzhxM" /><figcaption>Photo by <a href="https://unsplash.com/@bdchu614?utm_source=medium&amp;utm_medium=referral">Brendan Church</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Another example would be to think of it as a processor now having two arms to lift weights instead of just one arm.</p><p>So a computer with 6 physical cores and hyper-threading can handle 12 threads and thus has <em>12 logical cores</em>.</p><p>Let’s now dive deeper into the different execution techniques.</p><h3>II. Sequential, Concurrent &amp; Parallel execution</h3><h4>1. Sequential execution</h4><p>Running a set of tasks <strong><em>sequentially</em></strong> means the tasks are running one after the other. Each task is waiting until the one before it finishes its execution so it can start its own.</p><p>Sequential execution is also sometimes referred to as <em>serial</em> execution. So if programs are being executed serially, each program runs from beginning to end without interruption then the one after it can start executing, and so on.</p><h4>2. Concurrent execution</h4><p>Running tasks <strong><em>concurrently</em></strong> means several tasks have started their execution and are<em> progressing</em> together, just <strong>not</strong> simultaneously.</p><p>The easiest example here is to think of a chef that’s slicing onions and is also regulating the oven temperature as part of their recipe steps. Both of these tasks are independent of each other, so while the chef has started cutting the onions, they can stop their work and go regulate the oven temperature, then switch back to cutting the onions from where they left off, and so on.</p><p>The important point to note here is the <strong>switching</strong> happening between both tasks which are <strong>completely independent </strong>of each<strong> </strong>other but are still <strong>progressing at the same time</strong>, <em>just not simultaneously. </em>(Progressing here does not imply executing).</p><p>In short, a concurrent system can have two or more programs <em>in progress</em> at the same time but not being <em>executed</em> at the same time. One program can be suspended while some other gets executed, all while being able to make progress.</p><h4>3. Parallel execution</h4><p>Parallel execution is when tasks are getting <strong>executed at the same time. </strong>So here we’re referring to actual <strong>simultaneous execution.</strong></p><p>If we go back to our chef example, say we now have two chefs in the kitchen, so one can take care of cutting the onions while the other is in charge of regulating the oven temperature. Both of these independent tasks are now getting executed <strong>simultaneously</strong>, instead of having just one chef switch between them to get both of them done.</p><h4>4. Summary</h4><p>Sequential is about <strong><em>dealing</em> with one thing at a time</strong>, concurrency is about <strong><em>dealing</em></strong> <strong>with lots of things at once</strong> and parallelism is about <strong><em>doing</em> lots of things at once.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qieiATHxTug6SQSFkYMSwA.png" /><figcaption>Figure made by the author.</figcaption></figure><h3>III. Synchronous &amp; Asynchronous programming</h3><p>You might be wondering what these two terms have to do with the execution behaviors I just mentioned. Often, all of these terms (synchronous, sequential, etc) get bundled up together and so defining a clear boundary between them is going to help set these terms straight.</p><h4>1. Synchronous programming</h4><p>Synchronous programming is when events are <em>coordinated</em> together. In the context of code, this can be expressed as instructions that depend on each other to achieve the work, so they are <em>synchronized</em>.</p><p>More specifically, an instruction will wait for the result of the previous instruction to perform its job. This scenario can be implemented with <strong>sequential execution</strong> where only one instruction is running at any given time and the instruction after it depends on its result.</p><p><strong><em>So whenever you hear the term ‘synchronous’ you can think of sequential execution.</em></strong></p><h4>2. Asynchronous programming</h4><p>Asynchronous programming relies on <strong><em>non-blocking execution order</em></strong>. This means that an asynchronous program can take on multiple requests simultaneously and independently. These tasks can be run either <em>in parallel or concurrently.</em></p><p>In other words, asynchronous programming means a second task can begin executing, without waiting for an earlier task to finish. Tasks <em>do not wait for each other to finish</em> to start their execution.</p><p>The main takeaway from all this is that we are <strong>not</strong> stopping our execution to wait for these tasks to return their results.</p><h4>3. Summary</h4><p>The most common example used to illustrate the difference between synchronous &amp; asynchronous is the <em>fast-food</em> example:</p><p>Suppose you and your friend are at a fast-food restaurant. Your friend is picking a table to sit on while you’re submitting your orders to the cashier.</p><p>If this were a synchronous fast-food place, you’d have to stay by the cashier waiting until your order is ready and delivered to you from the kitchen before going back to your friend.</p><p>If this were an asynchronous fast-food place, you would be given a buzzer that will notify you when your food is ready. In the meantime, you’re free to go back to your friend, sit around, and chat until your order is ready.</p><p><strong>As a quick wrap-up:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGxmG5_T8L_jfQ_10yzDBw.png" /><figcaption>Figure made by the author</figcaption></figure><p>This is what you should think of when you’re comparing synchronous to asynchronous.</p><p>We can achieve<strong><em> synchronous behavior </em></strong>through <strong><em>sequential execution</em></strong> and we can achieve<strong><em> asynchronous behavior</em></strong> through<strong><em> concurrent or parallel execution.</em></strong></p><h3>IV. Multiprocessing &amp; Multithreading</h3><p>Now that we’ve covered some basic ground, let’s get into the actual work.</p><h4>1. Multiprocessing</h4><p>When we talk about multiprocessing, we’re talking about processes being executed <strong><em>simultaneously, </em></strong>this is what we’ve described before as <strong>parallel execution</strong><em>. </em>Following our previous explanations we know that this scenario is possible only with a multi-core processor setup, where we can <strong><em>execute</em></strong> multiple processes <strong><em>at the same time </em></strong>on different cores<strong><em>.</em></strong></p><p>Multiprocessing cannot be achieved on a single-core processor. Because we have just one CPU, there can’t be actual <strong><em>simultaneous</em></strong> execution happening. This leaves us with two options:</p><p>(1) Start multiple processes together and have them progress at the same time, <em>but not execute at the same time</em> just like we described using <strong>concurrent execution.</strong></p><p><em>Or</em></p><p>(2) Run just one process at a time and start another one only once the current one finishes its entire execution.</p><p><em>I’m pretty sure you can sense that option (1) will give us a much faster performance.</em></p><p>And indeed it does, we can start multiple processes together and execute each process independently to speed up their execution given our limited resources (a single-core CPU).</p><h4>2. Multithreading</h4><p>In multithreading, we’re talking about multiple <em>threads</em> executing at the same time in order for a process to execute faster.</p><p><em>“But if the instructions in our process run at the same time, won’t this affect their execution order and lead us to some unexpected state ?”</em></p><p>I’m glad you asked and quite frankly yes. Imagine we have the following code:</p><pre>x = 1<br>y = 1<br>y = x + 1<br>z = y + x</pre><p>Running the instruction ‘<em>z = y + x’ </em>before the ‘<em>y = x + 1’</em> will result in an incorrect result of <em>z = 2</em> instead of <em>3.</em></p><p>This is why, when trying to leverage multithreading within a process, it’s important to remember how and where it should be utilized.</p><p>It is most often used to run<strong> independent instructions</strong> within a process at the same time like the following:</p><pre>names = fetch_names_list()<br>birthdays = fetch_birthdays_list()</pre><p>Running these two instructions independently will cause no harm and will give our code a good speedup compared to running them sequentially.</p><p><em>“It can’t be that simple ! I smell something coming up …”</em></p><p>It is that simple, but you’re right there is something coming up.</p><p>We noticed how convenient multithreading is when trying to execute tasks like reading from a file, fetching information, etc. These are tasks involved in <em>input-output</em> (I/O) operations.</p><p>On the other hand, multiprocessing would be the most efficient when trying to execute more computational operations like the calculation example we saw earlier.</p><p>We can deduce something important from this observation:</p><blockquote><strong>Multiprocessing is good for CPU-bound tasks while Multithreading is good for I/O-bound tasks.</strong></blockquote><p><em>“Wait, bound what ? “</em></p><p>Just hang in there we’re almost done.</p><h3>V. CPU-bound &amp; IO-bound</h3><p>Let’s understand those two concepts now that we’ve introduced them in the previous section.</p><p>Simply put, CPU-bound tasks or programs are the tasks directly affected by the CPU’s power. The more powerful a CPU is, the faster these tasks are executed. Such tasks include image processing or matrix multiplication, etc.</p><p>IO-bound tasks depend on the speed of I/O (input/output) devices and how fast data can be handled. Such tasks include fetching data over the internet, reading inputs from a connected device or writing data to a file, etc.</p><p><em>“Oh wait, that’s it ? That’s pretty simple.”</em></p><p>Told ya to hang in there.</p><h3>VI. Final thoughts</h3><p>We’ve covered a lot of fundamentals in this article, and I hope you get the best out of it. The goal of this article is to make sure anyone can read and understand these concepts and the difference between them without having to scroll through several tutorial links and compare definitions to finally understand any of them.</p><p><em>(I’m talking from experience here).</em></p><p>It’s important to note that these concepts often differ between programming languages where we might prefer multithreading in some and multiprocessing in others. I’ll keep this topic for a future article, but it’s good to point that out.</p><p>I hope you’ve enjoyed reading this article. Voice your feedback if you’ve found this helpful or if you have any comments.</p><p>Thank you for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9c97ab11b7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>