<?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 Ibrahim on Medium]]></title>
        <description><![CDATA[Stories by Ibrahim on Medium]]></description>
        <link>https://medium.com/@ibrahim__?source=rss-21a50d94d603------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WPBTTLwDVGXG-r-poR_4LQ.jpeg</url>
            <title>Stories by Ibrahim on Medium</title>
            <link>https://medium.com/@ibrahim__?source=rss-21a50d94d603------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:41:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibrahim__/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[Understanding Synchronization Primitives and Techniques in Multithreaded Programming]]></title>
            <link>https://medium.com/@ibrahim__/understanding-synchronization-primitives-and-techniques-in-multithreaded-programming-565b71017d0e?source=rss-21a50d94d603------2</link>
            <guid isPermaLink="false">https://medium.com/p/565b71017d0e</guid>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[barriers]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[synchronicity]]></category>
            <dc:creator><![CDATA[Ibrahim]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 17:00:36 GMT</pubDate>
            <atom:updated>2024-12-19T17:02:17.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Parallel programming is essential for improving the performance of modern applications. One common approach is multithreading, where a single process uses multiple threads to execute different tasks at the same time.</p><p>While threads excel in resource sharing, this very trait introduces challenges such as starvation, deadlocks, and race conditions. To address these issues operating systems provide <strong>synchronization primitives, </strong>like <em>mutexes</em> and <em>semaphores</em> that are used to control access to shared resources.</p><p>This article covers the basics of these techniques and how they help manage concurrency in multithreaded environments.</p><h3>Mutex (Mutual Exclusion)</h3><p>A mutex is a structure that allows exclusive access to a shared resource, serving the function of a lock.</p><p>When a thread tries to access a critical section, it will check if the corresponding mutex is already locked. If it is, it means another thread is currently executing the critical part of the code. If it isn’t, it will lock it and then proceed to enter the critical section.</p><p>To better understand the Mutex, we can look at Petersons implementation, which supposes a total of 2 threads. The threads will have the ids 0 and 1, and <em>thread.getId() </em>would return the id of the current thread.</p><pre>def lock():<br>  id = thread.getId() # 0 or 1<br>  interested[id] = true<br>  victim = id # The thread sets itself as a victim<br>  while (interested[1 - id] and victim == id):<br>    continue <br><br>def unlock():<br>  interested[thread.getId()] = false</pre><p>In this pseudo-code, the thread sets <em>interested[id] </em>to true to indicate that it wants to access the critical section.</p><p>When there is no contention, the other thread won’t be interested and the lock will be successful. However, if there is contention, the last thread to lock the mutex will set itself as the victim, letting the other thread gets a chance to execute thanks to the condition <em>victim == id</em>.</p><h3>Semaphore</h3><p><em>Now what if we wanted to allow multiple threads to access a resource, but no more than a given number?</em></p><p>Suppose you have a <a href="https://en.wikipedia.org/wiki/Semaphore_(programming)#Library_analogy">library</a> with <strong>10 study rooms</strong> available for students. During exam season, these rooms are in high demand, so you use a <strong>counter </strong>system to <strong>manage access</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9JFx5ZXlJdNgF1xc" /><figcaption>Photo by <a href="https://unsplash.com/@giamboscaro?utm_source=medium&amp;utm_medium=referral">Giammarco Boscaro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The counter starts at 10, representing the available rooms. When a student requests a room, if the counter is greater than zero, you <em>decrement</em> it and assign a room to the student.</p><p>If it’s zero, the student must wait until another finishes and returns their room, at which point the counter is <em>incremented</em>. By having the students waiting in line, this also ensures that the order of arrival is respected.</p><p><strong>This system is akin to a semaphore.</strong> No more than a given number of threads can access the same resource, and the waiting threads can be ordered to avoid starvation: either by arrival, or by priority.</p><blockquote>When the maximum amount of threads allowed is 1, then you get a mutex!</blockquote><h3>Synchronization Techniques</h3><p>Thanks to synchronization primitives, we can build more complex or SPdifferent synchronization techniques. In the next paragraphs we’ll familiarize ourselves with a few of them.</p><h4>Barrier</h4><p>Imagine you were going on a group hike with your friends, but with a twist. Everybody would take different paths to reach the summit, where you all agreed you would meet.</p><p>Once everybody reaches the summit, you wave your goodbyes and keep going on your path.</p><p>Similarly, a barrier is used to wait for all threads to reach a certain point in the code execution, before allowing them to continue running. This can be useful when computing different data, that only makes sense when it’s all put together, like for example a matrix operation.</p><pre>def meet():<br>  n_threads += 1 # Increment number of current threads<br>  <br>  while (n_threads &lt; total threads): # Wait for everybody<br>    pass<br>  <br>  n_threads -= 1 # Decrement counter</pre><p>Above, a simplified psuedo code to picture what a barrier implementation could begin to look like. We would also possibly use a mutex to make sure that the variable <em>n_threads</em> is not modified by two threads at the same time, to avoid data loss.</p><h4>Spinlock</h4><p>A spinlock, is very similar to a mutex. In the classic implementation, a mutex will put a thread to sleep, when it can’t access the resource. A spinlock, however, keeps the thread “spinning” (or <em>busy waiting</em>) by constantly checking if the lock has been freed.</p><p>The appeal of the spinlock is its performance in low contention contexts, where it outperforms the mutex. In such cases, we can avoid the overhead that comes with changing contexts, allowing the thread to stay active and quickly acquire the lock.</p><p>However, in high-contention situations, spinlocks become wasteful, as they consume CPU resources while waiting for the lock to be released. The longer the spinlock is held, the more inefficient it becomes compared to a mutex.</p><h3>Conclusion</h3><p>Synchronization primitives like <strong>mutexes</strong> and <strong>semaphores</strong>, along with techniques such as <strong>barriers</strong> and <strong>spinlocks</strong>, are essential for managing concurrency in multithreaded programming. While many modern languages abstract away synchronization, understanding these concepts can help you troubleshoot and optimize your code, especially when dealing with problems like race conditions or performance bottlenecks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565b71017d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive into closures]]></title>
            <link>https://medium.com/@ibrahim__/deep-dive-into-closures-a00f2ad7f2e6?source=rss-21a50d94d603------2</link>
            <guid isPermaLink="false">https://medium.com/p/a00f2ad7f2e6</guid>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[lexical-scope]]></category>
            <category><![CDATA[first-class-function]]></category>
            <dc:creator><![CDATA[Ibrahim]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 22:24:04 GMT</pubDate>
            <atom:updated>2024-10-21T22:24:04.553Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Closures </em>are a recurring topic in technical interviews, often puzzling candidates who are asked to explain what they are. Understanding closures is not just a mental exercise, it can actually help you write better code.</p><p>The term <em>closure</em> can be a bit confusing because it’s used in different contexts. Most of the times, the closure will indicate a certain type of function, that can <strong>remember</strong> the variables outside of it. But what does this exactly mean?</p><figure><img alt="A scene from 1985 film Back to the Future in which main protagonist Marty McFly says “Hey, I’ve seen this one!”" src="https://cdn-images-1.medium.com/max/1024/1*QBfsxUwMJ-4YHfyw6gnteQ.png" /><figcaption>A closure referencing an external variable</figcaption></figure><p>In order to understand these function a bit better, we have to look at the other definition of closure, that Wikipedia defines as:</p><blockquote>A <strong>closure</strong>, also <strong>lexical closure</strong> or <strong>function closure</strong>, is a technique for implementing <a href="https://en.wikipedia.org/wiki/Lexically_scoped">lexically scoped</a> <a href="https://en.wikipedia.org/wiki/Name_binding">name binding</a> in a language with <a href="https://en.wikipedia.org/wiki/First-class_function">first-class functions</a>.</blockquote><p>Now that’s a lot to unpack… so let’s try to take this apart piece by piece.</p><h4>First-class functions</h4><p>A language with <a href="https://en.wikipedia.org/wiki/First-class_function">first-class functions</a> is one that allows functions to be <a href="https://en.wikipedia.org/wiki/First-class_citizen">first-class citizens</a>. First-class citizens, by <a href="https://en.wikipedia.org/wiki/Robin_Popplestone">Robin Popplestone</a>’s definition, are entities that can be:</p><ol><li>Passed as a parameter to functions</li><li>Returned by functions</li><li>Assigned to identifiers</li><li>Tested for equality</li></ol><p>In Python, these properties on functions would look like the following:</p><pre>def caller(function: Callable[[], None]) -&gt; None:<br>    function()<br><br>def foo() -&gt; None:<br>    def bar() -&gt; None:<br>        print(&quot;Foobar&quot;)<br>    return bar  # Can be returned<br><br>variable = foo()  # Assigning to identifier<br>caller(variable)  # Can be passed as a parameter<br>print(&quot;What&quot; if foo == caller else &quot;Nice!&quot;) # Can be checked for equality</pre><p>Some examples of languages with first-class functions are <strong>Python</strong>, <strong>Java </strong>(since Java 8, with some limitations), <strong>Javascript </strong>and others. <strong>C</strong>, for example is not a language with first-class functions.</p><h4>Lexical Scope and Name Binding Explanation</h4><p>Name binding is the process where an identifier is associated with a value, or a function. In your typical program this will take the form of variables declaration and assignment.</p><p>Name resolution is figuring out which name points to which value, at any point in the program execution or compilation. In other words, when the program encounters a name, it needs to <strong>resolve</strong> it — determine which value or function that name is associated with.</p><p>In <strong>lexically scoped</strong> languages, the rules for name resolution are determined by <strong>where</strong> the name is written in the source code and by the enclosing<strong> lexical contexts</strong>.</p><p>The first part, or where the name is defined in the program, is what allows you access parameters, as well as local and global variables, within a function for example.</p><pre>def foo(a: int) -&gt; None: # Parameter<br>  b = a + 1 # Local variable<br>  print(a, b) </pre><p>Since they are defined inside of the function, the name resolution will resolve successfully to their values.</p><p>The second part, which depends on lexical context, allows you to look for a variable outside of your current context. More specifically, if you don’t find the name of a variable within your local variables or parameters, you can look for it in your enclosing lexical context, from which you called the function.</p><pre>def init():<br>  counter = 0<br><br>  def increase() -&gt; None:<br>    # Declare it as nonlocal to allow modification (Python)<br>    nonlocal counter<br><br>    counter += 1 #Access variable outside of the functions context<br>    return counter<br>  return increase<br><br>inc = init()  <br>print(inc()) #1 <br>print(inc()) #2</pre><p>Think of it like searching for your keys. First, you check the room you’re in, which is like the local context — it’s the most immediate, so you look there first. If you don’t find the keys, you expand your search to nearby rooms — just like the program searches in the enclosing context if it can’t find the variable locally. Lexical scope works like that — it searches the most immediate scope and moves outward.</p><p>This is what closures are known for, being able to access data outside of their lexical context. Even better, the closure can access outer variables no matter how many times it’s called, making it ideal to keep state during function calls, or be passed as arguments to <a href="http://Higher-order function">higher order functions</a>.</p><h3>Practical uses</h3><p>In the following part we’ll briefly go over some practical examples to give some simple ideas about how to use closures.</p><h4>Encapsulation</h4><p>You can hide data and maintain state without exposing private variables. This is notably the case of the counter example, where the counter variable is hidden and only the result is returned for each call of the <em>increase()</em> function.</p><h4>Memoization</h4><p>When working with <em>deterministic </em>functions, you can store previous calls in a cache in order to optimize your program. If for the same inputs, you have the same outputs, you can save the association between them to avoid recomputing previously seen results.</p><p>This is also a top-down approach used in <strong>dynamic programming.</strong></p><pre>def memoize(func):<br>    cache = {}<br>    def memoized_function(x):<br>        if x not in cache:<br>            cache[x] = func(x)<br>        return cache[x]<br>    return memoized_function<br><br>@memoize #In Python you can just use @cache to achieve the same effect<br>def fibonacci(n):<br>    if n &lt;= 1:<br>        return n<br>    return fibonacci(n - 1) + fibonacci(n - 2)</pre><h4><strong>Functional Programming</strong></h4><p>Closures can also be leveraged for functional programming techniques, such as currying and partial application. These techniques, along with higher-order functions, can significantly improve the modularity and maintainability of your code.</p><pre>def addTo(a):<br>    def add(b):<br>        return a + b <br>    return add<br><br>print(addTo(3)(4)) #7</pre><p>While these techniques are part of functional programming, taking the time to learn and master them can broaden your perspective and provide you with more tools for your day-to-day programming journey.</p><h3>Conclusion</h3><p>In conclusion, closures are essential in programming as they let functions access and remember variables from their enclosing lexical contexts. This is particularly key in functional programming, where state management and higher-order functions are common. Understanding closures is an important advantage to be able to exploit the full potential of modern programming paradigms, allowing us to write flexible and reusable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a00f2ad7f2e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>