<?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 Medha on Medium]]></title>
        <description><![CDATA[Stories by Medha on Medium]]></description>
        <link>https://medium.com/@medhashri79?source=rss-38a1bdb2a62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Twg4Xjviwji-826Q</url>
            <title>Stories by Medha on Medium</title>
            <link>https://medium.com/@medhashri79?source=rss-38a1bdb2a62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:08:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@medhashri79/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[Can a Single-Core Handle Multithreading? If Yes, Then How?]]></title>
            <link>https://medium.com/@medhashri79/can-a-single-core-handle-multithreading-if-yes-then-how-7507346019f6?source=rss-38a1bdb2a62------2</link>
            <guid isPermaLink="false">https://medium.com/p/7507346019f6</guid>
            <dc:creator><![CDATA[Medha]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 12:42:49 GMT</pubDate>
            <atom:updated>2025-04-19T12:42:49.878Z</atom:updated>
            <content:encoded><![CDATA[<p>When we think of multithreading, we often imagine a blazing-fast multi-core processor juggling multiple threads at once. But what if we only have <strong>a single-core CPU</strong>? Can it <strong>really</strong> handle multiple threads?</p><p>The answer is: <strong>Yes, it can</strong> — but there’s a twist.</p><p>Let’s explore how.</p><h3>🧠 What Is Multithreading?</h3><p><strong>Multithreading</strong> is the ability of a CPU (or a program) to run <strong>multiple threads</strong> concurrently. A thread is the smallest unit of execution in a process — think of it like a mini-program within your program.</p><p>So, in theory, multithreading = doing multiple things at the same time.</p><p>But what happens when we have <strong>only one core</strong> to work with?</p><h3>🕹️ The Illusion of Parallelism</h3><p>In a <strong>single-core system</strong>, the CPU <strong>cannot</strong> physically execute more than one thread at the same instant.</p><p>But through a technique called <strong>context switching</strong>, it can give the <strong>illusion</strong> of doing multiple things at once.</p><h3>🔁 How It Works: Context Switching</h3><p>Here’s how a single-core CPU handles multithreading:</p><ol><li>The operating system (OS) divides CPU time into tiny slices — often just <strong>a few milliseconds</strong> long.</li><li>During each time slice, the CPU executes <strong>one thread</strong>.</li><li>When the time slice ends, the OS quickly <strong>saves the current thread’s state</strong> and <strong>loads the state of the next thread</strong>.</li><li>This switch happens so fast (thousands of times per second) that it <em>feels</em> like multiple threads are running at the same time.</li></ol><p>This mechanism is called <strong>time-sharing</strong> or <strong>preemptive multitasking</strong>.</p><h3>🧰 Example in Real Life</h3><p>Imagine you’re a single chef in a kitchen (single-core CPU), and you have to cook three dishes (three threads).</p><ul><li>You chop veggies for dish A (for 5 seconds),</li><li>Then switch to boiling pasta for dish B (for 5 seconds),</li><li>Then marinate meat for dish C (for 5 seconds),</li><li>Then go back to dish A…</li></ul><p>You’re only working on <strong>one dish at a time</strong>, but you’re <strong>constantly switching tasks</strong>, so it <em>feels</em> like all three are progressing together.</p><h3>🚀 Benefits of Multithreading on a Single Core</h3><ul><li><strong>Responsiveness</strong>: A UI thread can keep updating the screen while a background thread fetches data.</li><li><strong>Efficient I/O</strong>: While waiting for I/O (like file or network access), the CPU can switch to another thread.</li><li><strong>Cleaner Code Structure</strong>: Threads allow a logical separation of tasks, even if not run in true parallel.</li></ul><h3>⚠️ Limitations</h3><ul><li><strong>No True Parallelism</strong>: Performance is still limited by the single core.</li><li><strong>Context Switching Overhead</strong>: Switching between threads isn’t free — it takes time and resources.</li><li><strong>Thread Safety</strong>: Multiple threads may still access shared resources, leading to race conditions.</li></ul><h3>🧩 What About Hyper-Threading?</h3><p>Some CPUs have a <strong>single physical core</strong> but can simulate two logical cores using <strong>Simultaneous Multithreading (SMT)</strong> — like Intel’s <strong>Hyper-Threading</strong>.</p><p>This improves performance but is still not the same as having two real cores.</p><h3>🏁 Conclusion</h3><p>So, can a <strong>single-core processor</strong> handle multithreading?</p><p>✅ <strong>Yes — but only one thread runs at a time.</strong></p><p>It achieves multitasking through <strong>context switching</strong>, making it look like tasks are running in parallel. While not as powerful as true multi-core parallelism, single-core multithreading is still a valuable tool — especially for responsiveness and code organisation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7507346019f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Critical Sections, Threads, and the Mystery of int x — Stack vs Heap Explained]]></title>
            <link>https://medium.com/@medhashri79/critical-sections-threads-and-the-mystery-of-int-x-stack-vs-heap-explained-7a1c7f06f11e?source=rss-38a1bdb2a62------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a1c7f06f11e</guid>
            <dc:creator><![CDATA[Medha]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 14:42:05 GMT</pubDate>
            <atom:updated>2025-04-15T14:42:05.036Z</atom:updated>
            <content:encoded><![CDATA[<h3>Critical Sections, Threads, and the Mystery of int x — Stack vs Heap Explained</h3><p>In multithreaded programming, we often hear scary words like <strong>race conditions</strong>, <strong>critical sections</strong>, and <strong>data corruption</strong>. But let’s zoom in on a deceptively simple question:</p><blockquote>If two threads access a function in a critical section, and that function has a local variable int x, will two copies of x be created?</blockquote><blockquote>Let’s unpack this — using <strong>code, memory diagrams</strong>, and a look under the hood at how the <strong>stack and heap</strong> work in multithreaded programs.<br>Setting the Stage: Two Threads, One Function</blockquote><p>Imagine we have this function:cpp</p><pre>void myFunction() {<br>    int x;<br>    x = computeSomething();  // changing x<br>}</pre><p>Now, <strong>two threads</strong> call myFunction() simultaneously. Maybe it’s protected by a mutex, maybe it’s not — but the real question is:</p><h3>❓ Will the int x be shared between threads, or does each thread get its own?</h3><h3>💡 The Key Insight: x is a Local Variable</h3><p>In C++ (and most languages like C, Java, etc.), <strong>local variables</strong> are stored on the <strong>stack</strong>, and <strong>each thread has its own stack</strong>.</p><p>So the answer is:</p><p><em>✅ </em><strong><em>Yes, each thread gets its own copy of </em></strong><strong><em>x</em></strong><em>.</em></p><p>Even if two threads are calling the same function at the same time, their <strong>execution contexts are isolated</strong>, and so are their <strong>stack frames</strong>.</p><h3>Stack vs Heap: The Memory Layout</h3><p>Let’s visualise it.</p><p>🔸 Case: int x is a local variable (on the stack)</p><pre>Thread 1 Stack:              Thread 2 Stack:<br>+------------------+        +------------------+<br>| int x = ???      |        | int x = ???      |<br>| ...              |        | ...              |<br>+------------------+        +------------------+</pre><p>Each thread calls the function → each gets its own x → no overlap → <strong>safe, isolated memory</strong>.</p><h3>🔹 Case: x is allocated on the heap and shared</h3><pre>int* x = new int;<br>*x = computeSomething();</pre><p>Now we have:</p><ul><li>The <strong>pointer </strong><strong>x</strong> still on the stack (thread-local),</li><li>But the <strong>actual integer</strong> is on the <strong>heap</strong>.</li></ul><p>And if both threads are pointing to the same heap address?</p><p>💥 Boom — now you’re in <strong>shared memory territory</strong>, and you <strong>must</strong> protect access to *x using mutexes or other synchronisation tools.</p><h3>Heap layout:</h3><pre>Heap:<br>+-----------+<br>|  *x = ??? |  &lt;-- shared memory if pointer is shared<br>+-----------+</pre><h3>Thread 1 Stack:</h3><pre>int* x --&gt; [heap address]</pre><h3>Thread 2 Stack:</h3><pre>int* x --&gt; [same heap address]</pre><p>Now, <strong>both threads modify the same memory</strong>, and you can easily end up with <strong>race conditions</strong>.</p><h3>Code Example: Stack vs Heap in Action</h3><h3>✅ Safe — Local int x on Stack</h3><pre>void* threadFunc(void* arg) {<br>    int x = *(int*)arg;  // x is thread-local<br>    x += 5;<br>    printf(&quot;Thread %lu: x = %d\n&quot;, pthread_self(), x);<br>    return NULL;<br>}</pre><p>Each thread has its own x, no overlap.</p><h3>Unsafe — Shared Heap Variable</h3><pre>int* sharedX;</pre><pre>void* threadFunc(void* arg) {<br>    *sharedX += *(int*)arg;<br>    printf(&quot;Thread %lu: *sharedX = %d\n&quot;, pthread_self(), *sharedX);<br>    return NULL;<br>}</pre><p>This leads to unpredictable output unless sharedX is protected with a <strong>mutex</strong>.</p><h3>🧵 Summary</h3><ul><li><strong>Each thread has its own stack</strong>, so <strong>local variables like </strong><strong>int x are thread-safe</strong> by default.</li><li>If you allocate memory on the <strong>heap</strong> and <strong>share it</strong> between threads, you <strong>must synchronise access</strong>.</li><li>Critical sections help, but even inside them, <strong>understanding memory layout</strong> is key to avoiding subtle bugs.</li></ul><h3>🚀 Final Thoughts</h3><p>Multithreading can feel like magic — or madness. But once you understand how <strong>memory works across threads</strong>, a lot of that mystery fades away.</p><p>So next time you’re staring at an int x inside a function, remember: if it’s on the stack, each thread’s got its own. If it’s on the heap? Handle with care. 🔐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1c7f06f11e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>