<?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[Operating System CSCI 3300 - Medium]]></title>
        <description><![CDATA[This publication explores the theoretical foundations, architectural principles, we cover process scheduling, memory management, concurrency control, file systems, virtualization, and security mechanisms. - Medium]]></description>
        <link>https://medium.com/operating-system-csci3300?source=rss----2a57dafbe033---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Operating System CSCI 3300 - Medium</title>
            <link>https://medium.com/operating-system-csci3300?source=rss----2a57dafbe033---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:17:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/operating-system-csci3300" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Process Synchronization in Operating Systems]]></title>
            <link>https://medium.com/operating-system-csci3300/process-synchronization-in-operating-systems-44d1141c3235?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/44d1141c3235</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Amar Puaad]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:37:06 GMT</pubDate>
            <atom:updated>2025-05-26T11:37:05.935Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Process synchronization is a critical concept in operating systems that ensures concurrent processes or threads can access shared resources safely and without conflict. In this task given by our Operating System lecturer, <strong>Dr. Nur-Adib Maspo</strong>, we implemented three traditional synchronization problems using Python threads and semaphores:</p><ul><li><strong>Producer-Consumer</strong></li><li><strong>Readers-Writers</strong></li><li><strong>Dining Philosophers</strong></li></ul><p>Semaphores are used to control access to shared data and prevent race conditions, deadlocks, and starvation.</p><h3>Problem 1: Producer-Consumer (by Abdallah Bouher)</h3><p>This problem consists of:</p><ul><li><strong>Producers</strong>: generate items and place them into a shared buffer.</li><li><strong>Consumers</strong>: remove items from the buffer.</li></ul><p><strong>Key synchronization goals:</strong></p><ul><li>Producers must wait if the buffer is full.</li><li>Consumers must wait if the buffer is empty.</li><li>Only one thread can access the buffer at a time.</li></ul><p><strong>Semaphore solution:</strong></p><p>We used three semaphores:</p><ul><li><strong>empty (counting): </strong>number of empty slots.</li><li><strong>full (counting): </strong>number of filled slots.</li><li><strong>mutex (binary): </strong>ensures mutual exclusion when accessing the buffer.</li></ul><p>Full Python code for Producer-Consumer problem:</p><pre>import threading<br>import time<br>import random<br><br># ========================== CONFIGURATION ==========================<br>BUFFER_SIZE = 5  # Max items in buffer<br>PRODUCER_COUNT = 2<br>CONSUMER_COUNT = 2<br>ITEMS_PER_PRODUCER = 5<br><br># =========================== SHARED DATA ===========================<br>buffer = []  # Shared buffer<br><br># Semaphores<br>empty = threading.Semaphore(BUFFER_SIZE)<br>full = threading.Semaphore(0)<br>mutex = threading.Semaphore(1)<br><br>item_id_counter = 0<br>item_id_lock = threading.Lock()<br><br># =========================== PRODUCER ==============================<br>def producer(producer_id):<br>    &quot;&quot;&quot;Producer thread function.&quot;&quot;&quot;<br>    global item_id_counter<br><br>    for _ in range(ITEMS_PER_PRODUCER):<br>        time.sleep(random.uniform(0.1, 0.3))<br><br>        print(f&quot;[Producer {producer_id}] Waiting to enter critical section (waiting for empty slot)...&quot;)<br>        empty.acquire()<br><br>        print(f&quot;[Producer {producer_id}] Trying to acquire mutex...&quot;)<br>        mutex.acquire()<br>        print(f&quot;[Producer {producer_id}] ENTERED critical section.&quot;)<br><br>        with item_id_lock:<br>            item_id_counter += 1<br>            item = f&quot;Item-{item_id_counter}&quot;<br>        buffer.append(item)<br>        print(f&quot;[Producer {producer_id}] Produced {item} | Buffer: {buffer}&quot;)<br><br>        print(f&quot;[Producer {producer_id}] EXITED critical section.\n&quot;)<br>        mutex.release()<br>        full.release()<br><br># =========================== CONSUMER ==============================<br>def consumer(consumer_id):<br>    &quot;&quot;&quot;Consumer thread function.&quot;&quot;&quot;<br>    for _ in range(ITEMS_PER_PRODUCER):<br>        time.sleep(random.uniform(1.5, 2.0))<br><br>        print(f&quot;    [Consumer {consumer_id}] Waiting to enter critical section (waiting for full slot)...&quot;)<br>        full.acquire()<br><br>        print(f&quot;    [Consumer {consumer_id}] Trying to acquire mutex...&quot;)<br>        mutex.acquire()<br>        print(f&quot;    [Consumer {consumer_id}] ENTERED critical section.&quot;)<br><br>        item = buffer.pop(0)<br>        print(f&quot;    [Consumer {consumer_id}] Consumed {item} | Buffer: {buffer}&quot;)<br><br>        print(f&quot;    [Consumer {consumer_id}] EXITED critical section.\n&quot;)<br>        mutex.release()<br>        empty.release()<br><br># ============================ MAIN ================================<br>def main():<br>    &quot;&quot;&quot;Main function to start threads.&quot;&quot;&quot;<br>    producers = [threading.Thread(target=producer, args=(i,)) for i in range(PRODUCER_COUNT)]<br>    consumers = [threading.Thread(target=consumer, args=(i,)) for i in range(CONSUMER_COUNT)]<br><br>    for t in producers + consumers:<br>        t.start()<br>    for t in producers + consumers:<br>        t.join()<br><br>    print(&quot;\n[Main] Simulation Complete.&quot;)<br><br># ========================== ENTRY POINT ===========================<br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Output Explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Q7Xb5Irv8OjxgYDGU8Cakw.png" /></figure><blockquote>In this log, <strong>Producer 1</strong> is actively managing the buffer. Here’s a breakdown of the process:</blockquote><blockquote><strong>[Waiting for empty slot]</strong>: The producer initially waits to enter the critical section, indicating it requires an empty slot in the buffer to produce an item.</blockquote><blockquote><strong>[Acquiring mutex]</strong>: Once a slot becomes available, it attempts to acquire the mutex (a lock mechanism) to ensure exclusive access to the buffer.</blockquote><blockquote><strong>[Entering critical section]</strong>: After securing the mutex, Producer 1 enters the critical section, where it safely produces <strong>Item-1</strong> and updates the buffer. The buffer transitions from empty to containing <strong>[‘Item-1’]</strong>.</blockquote><blockquote><strong>[Exiting critical section]</strong>: The producer exits the critical section, releasing the mutex. This allows other threads (producers or consumers) to access the buffer.</blockquote><blockquote>By adding <strong>Item-1</strong>, the buffer now has one occupied slot. This action signals waiting <strong>producer</strong> and <strong>consumers</strong> that there is an item available to consume or produce. If the buffer reaches its capacity in subsequent operations, producers will wait again until slots free up.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*15bMnQA3cq7x7E5DRoOtWQ.png" /></figure><blockquote>· In this screenshot, <strong>Consumer 1 is actively managing the buffer. Here’s a breakdown of the process:</strong></blockquote><blockquote>1. <strong>[Waiting for full slot]</strong>:</blockquote><blockquote>o <strong>Consumer 1</strong> waits to enter the critical section, indicating it requires a <strong>full slot</strong> in the buffer (i.e., at least one item must be present to consume).</blockquote><blockquote>o If the buffer were empty, the consumer would remain blocked until a producer adds an item.</blockquote><blockquote>2. <strong>[Acquiring mutex]</strong>:</blockquote><blockquote>o Once the buffer contains items (here, initially including <strong>Item-3</strong>), Consumer 1 attempts to acquire the <strong>mutex</strong> (a lock ensuring no other thread modifies the buffer simultaneously).</blockquote><blockquote>3. <strong>[Entering critical section]</strong>:</blockquote><blockquote>o After securing the mutex, Consumer 1 enters the critical section.</blockquote><blockquote>o It <strong>consumes Item-3</strong>, removing it from the buffer. The buffer updates from:</blockquote><blockquote>[‘Item-3’, ‘Item-4’, ‘Item-5’, ‘Item-6’, ‘Item-7’] to : [‘Item-4’, ‘Item-5’, ‘Item-6’, ‘Item-7’]</blockquote><blockquote>4. <strong>[Exiting critical section]</strong>:</blockquote><blockquote>o Consumer 1 releases the mutex upon exiting, allowing other threads (producers or consumers) to proceed.</blockquote><blockquote>· <strong>Key Implications:</strong></blockquote><blockquote>· <strong>Buffer State</strong>: The buffer now has <strong>4 items</strong> (down from 5), freeing one slot.</blockquote><blockquote>· <strong>Signaling</strong>: This action n<strong>otifies waiting producers</strong> that a slot is now available (if they were blocked due to a full buffer) and <strong>allows other consumers</strong> to proceed if more items remain.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*-M9Cu_PfE9Q0H49vo6lXEA.png" /></figure><blockquote>In this screenshot, After the buffer becomes full, both Producer 0 and Producer 1 try to produce again but are blocked at empty.acquire() because the buffer is full (no empty slots). Meanwhile, Consumer 1 wakes up and sees that the buffer is full enough to consume. Consumer 1 acquires the mutex, enters the critical section, removes Item-1, and then exits, updating the buffer to have only 4 items now.</blockquote><blockquote>This <strong>frees up one slot</strong>, allowing <strong>a blocked producer to continue</strong> next.</blockquote><p><strong>Complete Simulation Screenshots:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Xa34Jgv7F_brnUOcXFa-OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*SxrJZ8Q_QHmziN_UwyQQuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*C8z7BcWYyjmYIy0WQ9bxJw.png" /></figure><h3>Problem 2: Readers-Writers (by Muhammad Amar)</h3><p>In the Readers-Writers problem:</p><ul><li>Multiple readers can read the shared data simultaneously.</li><li>A writer must have exclusive access to the shared resource.</li></ul><p>The challenge is to allow maximum concurrency (readers reading together) while still ensuring writers have exclusive access when necessary.</p><p><strong>Key synchronization goals:</strong></p><ul><li>Prevents data corruption.</li><li>Maximizes concurrency</li><li>There is no starvation due to proper semaphore release.</li></ul><p><strong>Semaphore Solution:</strong></p><ul><li><strong>readcount</strong> to track how many readers are active.</li><li>mutex to protect access to <strong>readcount</strong>.</li><li><strong>wrt</strong> (binary semaphore): controls access to the shared resource.</li></ul><p>Full Python code for Readers-Writers problem:</p><pre>import threading<br>import time<br>import random<br><br>readcount = 0<br>mutex = threading.Semaphore(1)<br>wrt = threading.Semaphore(1)<br>stop_event = threading.Event() <br><br>def reader(id):<br>    global readcount<br>    while not stop_event.is_set():<br>        time.sleep(random.uniform(0.5, 2))<br>        print(f&quot;[READER-{id}] wants to READ&quot;)<br><br>        mutex.acquire()<br>        readcount += 1<br>        if readcount == 1:<br>            wrt.acquire()<br>        mutex.release()<br><br>        print(f&quot;[READER-{id}] is READING... &quot;)<br>        time.sleep(random.uniform(1, 2))<br><br>        mutex.acquire()<br>        readcount -= 1<br>        if readcount == 0:<br>            wrt.release()<br>        mutex.release()<br><br>        print(f&quot;[READER-{id}] finished READING\n&quot;)<br><br>def writer(id):<br>    while not stop_event.is_set():<br>        time.sleep(random.uniform(1, 3))<br>        print(f&quot;[WRITER-{id}] wants to WRITE&quot;)<br><br>        wrt.acquire()<br>        print(f&quot;[WRITER-{id}] is WRITING... &quot;)<br>        time.sleep(random.uniform(1.5, 2.5))<br>        wrt.release()<br><br>        print(f&quot;[WRITER-{id}] finished WRITING\n&quot;)<br><br>threads = []<br>for i in range(3):<br>    t = threading.Thread(target=reader, args=(i+1,), name=f&quot;ReaderThread-{i+1}&quot;)<br>    t.start()<br>    threads.append(t)<br><br>for i in range(2):<br>    t = threading.Thread(target=writer, args=(i+1,), name=f&quot;WriterThread-{i+1}&quot;)<br>    t.start()<br>    threads.append(t)<br><br><br>time.sleep(10)<br>stop_event.set()  <br><br><br>for t in threads:<br>    t.join()</pre><p>Output Explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*B7-bzzkkWsh9hemwOSDFZA.png" /></figure><blockquote>All<strong> Readers</strong> are allowed to read at the same time. This shows that the <strong>readcount</strong> logic and semaphore synchronization are working correctly. No writer is active here, so readers proceed without waiting.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*oz0ROOfbDISe7SbT6yhLng.png" /></figure><blockquote>After the last reader finishes, it releases the <strong>wrt</strong> semaphore. then <strong>Writer 1</strong> gets access. Shows correct behavior where <strong>Writers</strong> wait for <strong>Readers</strong> to finish, then write alone.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*qSAjUXym5J3wKnaNSLjvrQ.png" /></figure><blockquote>Multiple threads are now requesting access. <strong>Writer 2</strong> was already waiting. After <strong>Writer 1</strong> finishes, <strong>Writer 2</strong> writes immediately due to no readers entered yet. <strong>Readers</strong> wait for their turn.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*o7vsHERgOlJN2b8kjxzWCg.png" /></figure><blockquote>After the <strong>Writers</strong> finished, multiple <strong>Readers</strong> read again. This shows that once the writer releases <strong>wrt</strong>, all waiting <strong>Readers</strong> can proceed in parallel.</blockquote><h3>Problem 3: Dining Philosopher (by Faizal Akhtar)</h3><p>Five philosophers sit at a table, with a fork between each pair. To eat, each philosopher needs both forks. This can lead to deadlock if all philosophers choose one fork and wait for the other.</p><p><strong>Semaphore Solution:</strong></p><ul><li>To ensure mutual exclusion, each fork has its own binary semaphore.</li><li>A waiter semaphore initialized to 4 (N-1 philosophers) prevents deadlock by ensuring that not all philosophers attempt to eat at the same time.</li></ul><p>From the semaphore solution we ensure:</p><ul><li>No deadlock occurs because the waiter limits concurrency and the ordered picking prevents circular waits.</li><li>No philosopher starves, as all eventually get permission to eat.</li><li>Mutual exclusion is maintained on forks, so no two philosophers use the same fork simultaneously.</li></ul><p>Full Python code for Dining Philosopher problem:</p><pre>import threading<br>import time<br>import random<br><br>class DiningPhilosophers:<br>    def __init__(self, num_philosophers=5):<br>        self.num = num_philosophers<br>        <br>        # Create one semaphore per fork (binary semaphore initialized to 1)<br>        # Each fork can be held by only one philosopher at a time<br>        self.forks = [threading.Semaphore(1) for _ in range(self.num)]<br>        <br>        # Waiter semaphore limits the number of philosophers trying to eat concurrently<br>        # Initialized to num - 1 to prevent deadlock scenario where all philosophers pick up one fork<br>        self.waiter = threading.Semaphore(self.num - 1)<br><br>    def wants_to_eat(self, philosopher_id):<br>        left_fork = philosopher_id  # Index of left fork<br>        right_fork = (philosopher_id + 1) % self.num  # Index of right fork (circular table)<br><br>        print(f&quot;[Philosopher-{philosopher_id}] is THINKING.&quot;)<br>        time.sleep(random.uniform(1, 3))  # Simulate thinking<br><br>        print(f&quot;[Philosopher-{philosopher_id}] is HUNGRY and trying to pick forks.&quot;)<br><br>        # Acquire waiter permission before picking forks<br>        # This prevents all philosophers from holding one fork and waiting indefinitely (deadlock)<br>        self.waiter.acquire()<br>        print(f&quot;[Philosopher-{philosopher_id}] got permission from waiter.&quot;)<br><br>        # To avoid circular wait condition (which causes deadlock), always pick up forks in the same order<br>        # The philosopher picks the fork with the smaller index first, then the higher index<br>        first_fork = min(left_fork, right_fork)<br>        second_fork = max(left_fork, right_fork)<br><br>        # Pick up the first fork (blocking if not available)<br>        print(f&quot;[Philosopher-{philosopher_id}] waiting for Fork-{first_fork}.&quot;)<br>        self.forks[first_fork].acquire()<br>        print(f&quot;[Philosopher-{philosopher_id}] picked Fork-{first_fork}.&quot;)<br><br>        # Pick up the second fork (blocking if not available)<br>        print(f&quot;[Philosopher-{philosopher_id}] waiting for Fork-{second_fork}.&quot;)<br>        self.forks[second_fork].acquire()<br>        print(f&quot;[Philosopher-{philosopher_id}] picked Fork-{second_fork}.&quot;)<br><br>        # Both forks acquired → philosopher can eat<br>        print(f&quot;[Philosopher-{philosopher_id}] is EATING.&quot;)<br>        time.sleep(random.uniform(2, 4))  # Simulate eating<br><br>        # Release forks after eating so others can use them<br>        self.forks[second_fork].release()<br>        print(f&quot;[Philosopher-{philosopher_id}] put down Fork-{second_fork}.&quot;)<br><br>        self.forks[first_fork].release()<br>        print(f&quot;[Philosopher-{philosopher_id}] put down Fork-{first_fork}.&quot;)<br><br>        # Release waiter permission allowing another philosopher to try eating<br>        self.waiter.release()<br><br>        print(f&quot;[Philosopher-{philosopher_id}] finished EATING and goes back to THINKING.\n&quot;)<br><br># Thread function that simulates a philosopher repeatedly thinking and eating until stopped<br>def philosopher_thread(dp: DiningPhilosophers, pid: int, stop_event: threading.Event):<br>    while not stop_event.is_set():<br>        dp.wants_to_eat(pid)<br><br>if __name__ == &quot;__main__&quot;:<br>    NUM_PHILOSOPHERS = 5  # Number of philosophers and forks<br>    dp = DiningPhilosophers(NUM_PHILOSOPHERS)<br>    stop_event = threading.Event()  # Event to stop threads cleanly<br><br>    threads = []<br>    # Start a thread for each philosopher<br>    for i in range(NUM_PHILOSOPHERS):<br>        t = threading.Thread(target=philosopher_thread, args=(dp, i, stop_event), name=f&quot;Philosopher-{i}&quot;)<br>        t.start()<br>        threads.append(t)<br><br>    time.sleep(15)  # Let the simulation run for 15 seconds<br>    stop_event.set()  # Signal threads to stop<br><br>    # Wait for all threads to finish<br>    for t in threads:<br>        t.join()<br><br>    print(&quot;Dining Philosophers simulation ended.&quot;)</pre><p>Full Output Screenshots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*qUM5d_1CSA7BO8vO388aPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*jnspzUgCEMlfOaiw5eWPEQ.png" /></figure><h3><strong>Conclusion</strong></h3><p>This assignment taught us how to understand and implement real-world synchronization problems with Python and semaphores. We demonstrated safe access to shared resources, mutual exclusion, and deadlock prevention with well-structured threading and semaphore logic. These simulations replicated real-world challenges in OS-level process management and provided hands-on experience with concurrent programming. We would like to our lecturer, <strong>Dr. Nur-Adib Maspo </strong>for assigning this task to us so we could understand and gain more knowledge regarding process synchronization in Operating Systems even more<strong>. </strong>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d1141c3235" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/process-synchronization-in-operating-systems-44d1141c3235">Process Synchronization in Operating Systems</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PROCESS SYNCHRONIZATION SIMULATION]]></title>
            <link>https://medium.com/operating-system-csci3300/process-synchronization-simulation-f63fe7a22be7?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/f63fe7a22be7</guid>
            <dc:creator><![CDATA[Azimmuhammad]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:36:40 GMT</pubDate>
            <atom:updated>2025-05-26T11:36:40.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kR07aM91ST18wTK1" /></figure><p>____________________________________________________________________________</p><p><strong>KULLIYYAH OF INFORMATION AND COMMUNICATION TECHNOLOGY</strong></p><p>____________________________________________________________________________</p><p><strong>CSCI 2304 — OPERATING SYSTEM</strong></p><p><strong>SEMESTER 2, 2024/2025</strong></p><p><strong>SECTION 6</strong></p><p><strong>PROJECT REPORT</strong></p><p><strong>Process Synchronization Simulation</strong></p><p><strong>GROUP: 5</strong></p><p><strong>PREPARED BY:</strong></p><p><strong>NAME</strong></p><p><strong>MATRIC NO.</strong></p><p>MUHAMMAD AZIM BIN MUSTAFA KHALIL</p><p>2313415</p><p>MUHAMMAD DANISH ASYRAAF BIN MOHD PARID</p><p>2313409</p><p>MUHAMMAD FAIZ NABIL BIN FAIZAN</p><p>2315641</p><p>ADAM MUZZAMMIL BIN MOHD SAIFUL NIZAM</p><p>2313233</p><p>MUHAMMAD DINIE HAIQAL BIN HAMZAH</p><p>2312409</p><p><strong>Instructed by:</strong></p><p>Dr. Adib Maspo</p><p><strong>Introduction</strong></p><p>This report outlines the execution of developed process synchronization simulations. The project tackles the traditional synchronization issues of the Producer-Consumer problem (bounded buffer), the Readers-Writers problem, and the Dining Philosophers problem. These simulations utilize semaphores in a Python threading context to handle concurrent processes and guarantee safe access to shared resources. The main aim is to show a complete comprehension of crucial mechanisms and their practical use in reducing possible concurrency problems such as race conditions, deadlock, and starvation. This will help maintain the integrity of shared data and ensure that concurrent processes run in an orderly manner.</p><ol><li><strong>Bounded Buffer Problem</strong></li></ol><p>The bounded buffer problem involves the producer (process that produces information, resources and items inside the buffer) and the consumer (process that consumes information, resources and items inside the buffer). Before we get into the problem, we must understand how the producer and consumer work inside the bounded buffer. A bounded buffer is a temporary data storage before an exchange, which has the fixed value of buffer slots. In order for the producer to insert the item into the buffer, it must have an empty slot. Meanwhile, the consumer needs to consume the items from the filled slot and not from the empty slot. Based on this, there are three problems that need to be solved which are :</p><ul><li>The producer must not insert data when the buffer is full</li><li>The consumer must not remove data when the buffer is empty.</li><li>Producer and consumer must not insert or remove data simultaneously or coherently.</li></ul><p>Based on our study through the Chapter 6: Synchronization Tools and Chapter 7: Synchronization Examples, the most suitable solution for this problem is using semaphores or specifically semaphores’ functions consist of</p><ul><li>wait()</li><li>signal()</li><li>mutex : a binary semaphore 0 &amp; 1 which basically clocks that need to acquire it and release it</li><li>empty : a counting semaphore that has an initial value of n slots in the buffer</li><li>full : counting semaphore that has an initial value of 0</li></ul><p>We will look up to the codes for better understanding on how the semaphore is being used in real world situation</p><p><strong>Code</strong></p><p><strong>import threading</strong></p><p><strong>import time</strong></p><p><strong>import random</strong></p><p><strong>buffer = []</strong></p><p><strong>buffer_size = 5</strong></p><p><strong>#Semaphores</strong></p><p><strong>empty = threading.Semaphore(buffer_size) #Buffer starts with empty (5 empty slots)</strong></p><p><strong>full = threading.Semaphore(0)</strong></p><p><strong>mutex = threading.Lock()</strong></p><p>In this section of code, we initialize the buffer’s content to NULL and set the buffer size to 5, as it is a bounded buffer. We also initialized the empty, full, and mutex based on the rules and their function as mentioned before.</p><p><strong>def producer():</strong></p><p><strong>for _ in range(5):</strong></p><p><strong>item = random.randint(1, 100)</strong></p><p><strong>print(“[PRODUCER] Waiting to produce…”)</strong></p><p><strong>empty.acquire()</strong></p><p><strong>mutex.acquire()</strong></p><p><strong>print(“[PRODUCER] Entering critical section”)</strong></p><p><strong>buffer.append(item)</strong></p><p><strong>print(f”[PRODUCER] Produced: {item} | Buffer: {buffer}”)</strong></p><p><strong>print(“[PRODUCER] Exiting critical section\n\n”)</strong></p><p><strong>mutex.release()</strong></p><p><strong>full.release()</strong></p><p><strong>time.sleep(1)</strong></p><p>This section is for the function of Producer which the semaphores are being used inside this function. Before the producer can enter the critical section, it needs to wait until the empty slot of the buffer &gt; 0 and needs to wait for acquiring the lock if the consumer is still inside the critical section. As we learned, the producer and consumer cannot be executed simultaneously.</p><p>After the producer is able to enter the critical section, it will append or add the item based on the random number in the range of 1–100 in this line of code: <strong>item = random.randint(1, 100).</strong></p><p>Then, the producer will exit from the critical section and release the lock and the number of filled buffer slots will be increased by 1.</p><p><strong>def consumer():</strong></p><p><strong>for _ in range(5):</strong></p><p><strong>print(“\n\n[CONSUMER] Waiting to consume…”)</strong></p><p><strong>full.acquire()</strong></p><p><strong>mutex.acquire()</strong></p><p><strong>print(“[CONSUMER] Entering crtical section”)</strong></p><p><strong>item = buffer.pop(0)</strong></p><p><strong>print(f”[CONSUMER] Consumed: {item} | Buffer: {buffer}”)</strong></p><p><strong>print(“[CONSUMER] Exiting crtical section\n\n”)</strong></p><p><strong>mutex.release()</strong></p><p><strong>empty.release()</strong></p><p><strong>time.sleep(2)</strong></p><p>This section is for the function of the Consumer, where the semaphores are being used inside this function. Before the consumer can enter the critical section, it needs to wait until the full slot of the buffer &gt; 0 and needs to wait for acquiring the lock if the producer is still inside the critical section. As we learned, the producer and consumer cannot be executed simultaneously.</p><p>After the consumer is able to enter the critical section, it will remove the item from the buffer based on this line of code: <strong>item = buffer.pop(0).</strong></p><p>Then, the consumer will exit from the critical section and release the lock, and the number of empty buffer slots will be increased by 1.</p><p><strong>t1 = threading.Thread(target=producer)</strong></p><p><strong>t2 = threading.Thread(target=consumer)</strong></p><p><strong>t1.start()</strong></p><p><strong>t2.start()</strong></p><p><strong>t1.join()</strong></p><p><strong>t2.join()</strong></p><p><strong>print(“Simulation done.”)</strong></p><p>This Python code creates two threads: one for a producer function and another for a consumer function. By calling start() on each thread, both functions begin executing concurrently. The join() method is then used to pause the main program until both threads have finished their tasks, ensuring that the main thread waits for their completion before proceeding. Finally, the program prints “Simulation done.” to indicate that both threads have completed their execution.</p><p><strong>Outputs</strong></p><p><strong>[PRODUCER] Waiting to produce…</strong></p><p><strong>[CONSUMER] Waiting to consume…</strong></p><p><strong>[CONSUMER] Entering critical section</strong></p><p><strong>[CONSUMER] Consumed: 49 | Buffer: [78, 88, 19, 18]</strong></p><p><strong>[CONSUMER] Exiting critical section</strong></p><p><strong>[PRODUCER] Entering critical section</strong></p><p><strong>[PRODUCER] Produced: 42 | Buffer: [78, 88, 19, 18, 42]</strong></p><p><strong>[PRODUCER] Exiting critical section</strong></p><p><strong>2. Readers-Writers Problem</strong></p><p>Reader-Writer problem is a classic concurrency control problem that arises when multiple processes need to access a shared resource, like a file or a database. These processes can be divided into two types:</p><ul><li>Readers: Processes that only need to read the data from the shared resource; they don’t modify it.</li><li>Writers: Processes that need to modify (write to) the shared resource.</li></ul><p>The main challenge is to manage concurrent access to the resource in a way that satisfies these conditions:</p><ul><li>Multiple readers can access the shared resource simultaneously.</li><li>Only one writer can access the shared resource at any given time.</li><li>While a writer is accessing the shared resource, no other readers or writers can access it.</li></ul><p>The Solution Code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*cj0od4BKuURSORDB" /></figure><p>This part is about controlling who can use shared resources. Think of semaphores as traffic lights. They help keep things flowing smoothly and safely. The read_count variable tells us how many readers are currently using the data. To prevent problems, the mutex semaphore acts like a manager. It makes sure only one thread can change the read_count at a time. The write_lock semaphore is another manager. It controls who can use the actual data. This stops things from getting mixed up and prevents data from being ruined by making sure only one writer can change it at any moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*8BWdInAL-KYExJeo" /></figure><p>The reader function shows what a reader does. Each reader has its own ID. It keeps trying to get to the shared data. First, the reader needs to ask permission to see how many other readers are already there (using mutex.acquire()). If it’s the very first reader, it also needs to take control of the data so that writers can’t change it while it’s reading. Once a reader is allowed to access the data, it reads it. To show that reading takes time, it pauses for a bit. Then, it says that it’s done with the data, allowing other readers or writers to use it. If this reader is the last one reading, it also releases the control that was preventing writers from accessing the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*id0Qf_4hoEDJkxSC" /></figure><p>Each writer has its own ID and always tries to change the shared data. Before a writer can change anything, it must get full control of the data (using write_lock.acquire()). This makes sure no other readers or writers are using the data at that moment. Once the writer has control, it changes the data. To show that writing takes time, it pauses for a little bit. After it’s done writing, it gives up its full control, so others can use the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*M32ZgyWhRa_tfaET" /></figure><p>This final block executes the entire process. It’s like the director of a play, creating the actors (threads) and starting their performances. It first creates multiple reader and writer threads, each running their respective functions. Then, it starts these threads, allowing them to execute concurrently.</p><p>Finally, it keeps the main program running, acting as a stage manager, and gracefully handles any interruptions, ensuring a smooth and controlled termination of the program.</p><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*Rno6TGm9o-1ibx2z" /></figure><p><strong>3. The Dining Philosopher Problem</strong></p><p>The Dining Philosophers Problem is a classic synchronization problem in computer science, often used to illustrate the challenges of concurrent access to shared resources. It involves five philosophers who sit around a table, alternating between two activities: thinking and eating. To eat, each philosopher requires two forks — one on their left and one on their right. Since each fork is shared between neighboring philosophers, proper synchronization is essential to prevent multiple philosophers from using the same fork simultaneously.</p><p><strong>Problem Statement and Challenges</strong></p><p>The main challenges in the Dining Philosophers Problem are avoiding deadlock, starvation, and race conditions. A deadlock occurs if all philosophers simultaneously pick up the left fork and wait forever for the right fork, creating a circular wait with no resolution. Starvation can occur if some philosophers are continually prevented from eating due to the scheduling or logic of resource allocation. Solving these issues requires a synchronization mechanism that ensures mutual exclusion, bounded waiting, and progress.</p><p><strong>Solution Design</strong></p><p>To address these challenges, our implementation uses Python’s threading module and semaphores. Each fork is represented by a binary semaphore (Semaphore(1)), allowing only one philosopher to hold a fork at any time. To prevent deadlock, we introduce a counting semaphore — referred to as a “waiter” — initialized to 4 (one less than the number of philosophers). This ensures that only four philosophers can attempt to pick up forks at the same time, guaranteeing that at least one will be able to eat and break the circular waiting condition.</p><p><strong>Synchronization Mechanism</strong></p><p>Each philosopher is modeled as a separate thread. The philosopher first acquires the waiter, then picks up the left and right forks, eats, and finally releases the forks and the waiter. This approach guarantees exclusive access to forks, maintains fairness, and avoids both deadlock and starvation. The output of the program includes state transitions such as “thinking,” “hungry,” “eating,” and “putting down forks,” providing a clear trace of each philosopher’s behavior.</p><p><strong>Outcome and Observations</strong></p><p>The simulation runs continuously and demonstrates a stable, deadlock-free system. Every philosopher eventually gets a chance to eat, and the use of semaphores ensures synchronized and conflict-free access to the shared forks. The solution is simple yet effective, and it successfully showcases the power of semaphores in handling concurrent processes and critical section management.</p><p><strong>Code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*ARskLDIfRiEmfdM_jSs1JQ.png" /></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*5SF3GpYuR4IDlPneAuGxKw.png" /></figure><p><strong>Conclusion</strong></p><p>The simulations detailed in this report present a significant demonstration of how effective computation models are in tackling fundamental challenges of process synchronization. The effective management of shared resources and critical sections in the Producer-Consumer, Readers-Writers, and Dining Philosophers problems has been made possible by the implementation of counting and binary semaphores. The outputs of the simulation confirm the proper functioning of the semaphore logic, demonstrating its effectiveness in averting deadlock, starvation, and race conditions. This project highlights the significance of semaphores as an essential tool in the design and implementation of concurrent systems, guaranteeing safety and efficiency in resource management and process execution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f63fe7a22be7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/process-synchronization-simulation-f63fe7a22be7">PROCESS SYNCHRONIZATION SIMULATION</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process Synchronization Simulation]]></title>
            <link>https://medium.com/operating-system-csci3300/process-synchronization-simulation-2c0b6214b182?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c0b6214b182</guid>
            <dc:creator><![CDATA[Haris]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:35:59 GMT</pubDate>
            <atom:updated>2025-05-26T11:35:59.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Process synchronization is a concept that is used to ensure multiple threads and processes the can run simultaneously without interfering with each other. Its main function is to guarantee that multiple processes can access shared resources without disturbing each other and removing the possibility of inconsistent data through concurrent access. This can be done with techniques that include <strong>semaphores</strong>, <strong>monitors </strong>and <strong>critical sections</strong>.</p><p>Three common problems that can be associated with process synchronization are <strong>the Producers-Consumers problem</strong>, <strong>the Readers-Writers problem</strong> and <strong>the Dining-Philosophers problem</strong>.</p><blockquote><strong><em>1. Problem Explanations</em></strong></blockquote><h4>- The Producers-Consumers Problem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*PXB-MJ18PeDlPc71.png" /><figcaption>Visualization of the Producer-Consumer problem</figcaption></figure><p>This problem is a type of synchronization problem that begins with code that houses the existence of two specific entities, the Producer and the Consumer. The producer functions to add and generate data or resources that would be added to shared buffer between the producer and the consumer. The consumer functions to retrieve and consume the data stored in the shared buffer. The shared buffer itself is a memory region that has a fixed-size and serves as the queue for the data transfer between the producer and the consumer. The problem arises due to two specific conditions:</p><ol><li>Producers are unable and will not continue to add data when the shared buffer is filled</li><li>Consumers are unable and will not consume data when the shared buffer is empty</li></ol><p>Both of these situations together cause a race condition to occur as both the producer and consumer are try to access and manipulate data inside the shared buffer concurrently which may cause the outcome of the process to differ from the desired outcome.</p><h4>- The Readers-Writer Problem</h4><p>This problem occurs due to the presence of two entities, the reader and the writer. The reader is only capable of reading the data set whereas the writer is both able to manipulate and access the data set. This in turn causes a concurrent based issue when the entities create multiple instances of attempts to access the data set at the same time. This can occur in two different ways:</p><ol><li>The First Reader-Writer Problem — A situation where a writer process never writes</li><li>The Second Reader-Writer Problem — A situation where when a writer is ready to write in the data set, no newly created reader instances are able to read</li></ol><p>This in turn can cause starvation to occur as either the reader or writer process can be stuck in a waiting queue that is too long and borderline endless</p><h4>- The Dining-Philosophers Problem</h4><p>This problem starts with an N amount of philosophers who sit around a circular sized table with one bowl of food in the middle with a set of utensils besides their plate, one on each side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unnSxzHoaAX462KYZ2Ljiw.png" /><figcaption>Visualization of the Dining-Philosophers problem</figcaption></figure><p>The philosophers do not interact with each other and only sit at the table to focus on two actions, eating and thinking. The philosopher will occasionally pick up two utensils (resource) one at a time in order to begin eating from the bowl and will only release these two utensils once they are finished. The problem arises when specific events happen around the table.</p><ol><li>The first problem is when each philosopher collectively picks up the utensil on their right which in turn would case every one of them having to wait for their neighbour to finish so they can pick up the utensil on their left. This in turn causes a deadlock to be created</li><li>The second problem arises when some philosophers are never unable to begin eating as their neighbours may constantly be picking up the utensil without actually using them. This creates a starvation situation where the philosophers are just unable to ever begin their process.</li></ol><blockquote><strong><em>2. Application of semaphores</em></strong></blockquote><p>A <strong>semaphore</strong> is a variable used to control access to shared resources. There are two types of semaphore:</p><ul><li><strong>Counting Semaphore</strong>: Tracks resource availability (e.g., empty slots in a buffer)</li><li><strong>Binary Semaphore (Mutex)</strong>: Acts as a lock for mutual exclusion</li></ul><h3>1. Producer-Consumer problem</h3><p>Three semaphores were used in this problem:</p><ul><li><strong>empty</strong>: Counts empty slots in the buffer (initialized to buffer size)</li><li><strong>full</strong>: Counts filled slots (initialized to 0)</li><li><strong>mutex</strong>: A binary semaphore to enforce mutual exclusion (acts as a lock)</li></ul><p><em>Step-by-Step Solution</em></p><h4>Producer Workflow</h4><ol><li><strong>Produce an item</strong> (e.g., generate data).</li><li><strong>Wait for an empty slot</strong> using empty.acquire().</li><li><strong>Acquire the mutex</strong> to enter the critical section (CS).</li><li><strong>Add the item</strong> to the buffer.</li><li><strong>Release the mutex</strong> to exit the CS.</li><li><strong>Signal full.release()</strong> to indicate a new item is available.</li></ol><h3>Consumer Workflow</h3><ol><li><strong>Wait for a filled slot</strong> using full.acquire().</li><li><strong>Acquire the mutex</strong> to enter the critical section.</li><li><strong>Remove an item</strong> from the buffer.</li><li><strong>Release the mutex</strong> to exit the CS.</li><li><strong>Signal empty.release()</strong> to free up a slot.</li><li><strong>Consume the item</strong> (e.g., process data).</li></ol><h3>How Semaphores Prevent Issues</h3><ol><li><strong>Buffer Overflow: <em>empty </em></strong>semaphore blocks producers if the buffer is full.</li><li><strong>Buffer Underflow</strong>: <strong><em>full </em></strong>semaphore blocks consumers if the buffer is empty.</li><li><strong>Race Conditions</strong>: <strong><em>mutex </em></strong>ensures only one thread (producer or consumer) accesses the buffer at a time.</li></ol><p><em>Screenshots of the simulation</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*N9ZnvEtGWdff7T4J" /><figcaption>Full screenshot of the entire code</figcaption></figure><h4>Semaphore Initialization:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*5FnyXek51SHZjNzq" /></figure><ul><li><strong>empty</strong>: Initialized to BUFFER_SIZE (5). This ensures producers can add up to 5 items before blocking</li><li><strong>full</strong>: Starts at 0 because the buffer is initially empty. Consumers must wait until items are added</li><li><strong>mutex</strong>: Acts as a lock to enforce mutual exclusion when accessing the buffer</li></ul><h4>Producer Section:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*W8LNNue2iEsNrpPw" /></figure><ul><li><strong>Prevents Overflow</strong>: empty.acquire() blocks the producer if the buffer is full (no empty slots).</li><li><strong>Critical Section</strong>: The mutex ensures only one producer/consumer modifies the buffer at a time.</li><li><strong>Signaling</strong>: full.release() increments the full semaphore, notifying consumers that an item is ready.</li></ul><h4>Consumer Section:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*WEUTFLN1f3HAoeb5" /></figure><ul><li><strong>Prevents Underflow</strong>: full.acquire() blocks the consumer if the buffer is empty.</li><li><strong>Critical Section</strong>: The mutex ensures safe removal of items from the buffer.</li><li><strong>Signaling</strong>: empty.release() increments the empty semaphore, allowing producers to add new items.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*I9TadgNk16HaK7-a" /><figcaption>Sample Output Snippet</figcaption></figure><h4>- Synchronization Flow</h4><h4>The synchronization using semaphore occur by following flow:</h4><ol><li><strong>Producer 1</strong> generates item 57:</li></ol><ul><li>Calls <strong><em>empty.acquire</em></strong>() (now empty=4).</li><li>Acquires <strong><em>mutex</em></strong>, adds 57 to <strong><em>buffer</em></strong>, releases <strong><em>mutex</em></strong>.</li><li>Calls<strong> <em>full.release</em></strong>() (now full=1).</li></ul><p><strong>2. Consumer 1</strong> wants to consume:</p><ul><li>Calls <strong><em>full.acquire</em></strong>() (now full=0).</li><li>Acquires <strong><em>mutex</em></strong>, removes 57, releases <strong><em>mutex</em></strong>.</li><li>Calls <strong><em>empty.release</em></strong>() (now empty=5).</li></ul><p><strong>- Deadlock Prevention in the Producer-Consumer Code</strong></p><p>Deadlock is avoided by strictly adhering to the <strong><em>order of semaphore acquisition</em></strong>: <em>producers</em> and <em>consumers </em>always acquire <strong><em>empty/full</em></strong> <em>before</em> mutex. This ensures no <strong><em>thread</em></strong> holds the <strong><em>mutex </em></strong>while waiting for another <strong><em>semaphore</em></strong>, eliminating circular waiting. For example, a <em>producer </em>first ensures an empty slot exists (<strong><em>empty.acquire()</em></strong>) <em>before</em> locking the buffer (<strong><em>mutex.acquire()</em></strong>), so it never blocks the <strong><em>buffer </em></strong>while waiting for space. Similarly, consumers wait for items (<strong><em>full.acquire()</em></strong>) before accessing the buffer. <strong><em>Starvation</em></strong> is prevented because <strong><em>semaphores </em></strong>(in Python) use a <strong><em>FIFO queue</em></strong> for blocked <strong><em>threads</em></strong>, ensuring <strong><em>fairness</em></strong>, and the code’s balanced workload (producers and consumers finish after fixed iterations) guarantees all threads terminate. By prioritizing resource availability checks (empty/full) over mutual exclusion (mutex), the design inherently avoids deadlock and starvation.</p><h3>2. <em>Readers-Writers Problem</em></h3><p>The semaphores are applied through a binary semaphore in this code. <strong><em>mutex </em></strong>in the code is an example of a binary semaphore because it protects the <strong><em>readers_count</em> </strong>variable to ensure only one thread modifies it simultaneously. Furthermore, to ensure that a race doesn’t happen between multiple readers when incrementing/decrementing the <strong><em>readers_count</em></strong> variable. In addition, <strong><em>rw_mutex</em></strong> is also an example of a binary semaphore implemented in the code. The function of <strong><em>rw_mutex</em></strong> is to give the writers exclusivity so they can access the <strong><em>book_name</em></strong> variable. Writers must acquire the lock before modifying the <strong><em>book_name</em> </strong>variable.</p><h3>Initialization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*TBsuT7Ht5BKNRCIN" /><figcaption>Screenshot of the initialization</figcaption></figure><p><strong>Imports</strong>: Necessary for the modules involving <strong>threading, timing, and randomness</strong></p><p><strong>Shared Resources</strong>:</p><ul><li><strong><em>book_name</em></strong>: The shared data that both readers and writers access</li><li><strong><em>readers_count</em></strong>: Tracks how many readers are currently reading</li></ul><p>Synchronization Primitives:</p><ul><li><strong>mutex</strong>: Protects the <strong><em>readers_count</em></strong></li><li><strong>rw_mutex</strong>: Protects the actual book name (<strong><em>book_name</em></strong>)</li><li><strong>Fairness</strong>: Makes sure that no thread is starving through enforcing order</li></ul><h3>Reader Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mdKgMJNB9JF7wHl6" /><figcaption>Screenshot for Reader Function</figcaption></figure><p>Entry Protocol:</p><ol><li>Acquires a fairness <strong>semaphore </strong>for the prevention of starvation</li><li>Uses a <strong>mutex </strong>to alter the incrementation of <strong><em>readers_count</em></strong> safely</li><li>First reader acquires the write lock (<strong><em>rw_mutex</em></strong>)</li></ol><p>Reading: Accesses the shared <strong><em>book_name</em></strong> variable</p><p>Exit Protocol:</p><ol><li>Uses a <strong>mutex </strong>to decrement <strong><em>readers_count</em></strong> safely</li><li>The last reader releases the write lock</li></ol><h3>Writer Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*48cX8meIeIWEyYKI" /><figcaption>Screenshot for Writer Function</figcaption></figure><p>Entry Protocol:</p><ol><li>Acquires the fairness <strong>semaphore</strong></li><li>Acquires exclusive write lock (<strong><em>rw_mutex</em></strong>)</li></ol><p>Writing: Modifies the shared <strong><em>book_name</em></strong> variable</p><p>Exit Protocol: Releases <strong>both locks</strong></p><h3>Main Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*AlkmC9aomZUGwskG" /></figure><p>Setup: Creates 3 <strong><em>readers</em></strong> and 2 <strong><em>writer</em></strong> threads</p><p>Execution:</p><ul><li>Randomly shuffles thread execution order</li><li>Starts threads with staggered timing</li><li>Waits for all threads to complete</li><li>Screenshots of the simulation</li></ul><p><strong>Simulation Screenshots</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*FgkFHH1eLPSY2NIl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*en_qZiVVlzNEEPTJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*T4jsKfFDbNoIHWPG" /></figure><h3><em>3. The Dining Philosophers Problem</em></h3><h4>The Scenario:</h4><p>Imagine five <strong>philosophers </strong>sitting around a circular table, alternating between thinking and eating. Between each <strong>philosopher </strong>is a single fork (five forks total). To eat, a <strong>philosopher </strong>needs both their left and right forks simultaneously.</p><h4><strong>The Core Problem</strong>:</h4><p>When all <strong>philosophers </strong>simultaneously pick up their left fork, they all wait indefinitely for their right fork (which is held by their <em>neighbor</em>) — this creates a deadlock where no progress is made. This demonstrates a common synchronization challenge in computing when multiple processes compete for shared resources.</p><h4>Key Challenges:</h4><p><strong>Deadlock Prevention</strong>: Ensuring the system doesn’t lock up</p><p><strong>Starvation Avoidance</strong>: Guaranteeing all philosophers eventually eat</p><p><strong>Concurrency Control</strong>: Managing simultaneous access to shared resources (forks)</p><h3>How Semaphores Solve the Problem</h3><p>Semaphores are synchronization primitives that:</p><ul><li>Maintain an <strong>internal counter</strong></li><li>Provide <strong><em>acquire</em></strong><em>()</em> (decrement) and <strong><em>release</em></strong><em>()</em> (increment) operations</li><li>Block threads when counter reaches zero</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*nYhxHHu_vqCCIJeD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*xT8F6MO_oePQXakP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*jpXmXd6I0f3-A3DM" /></figure><h4><strong>1. Core Structure</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*qOrum-jX6SeCSq9V" /></figure><ul><li><strong>Forks</strong>: Represented as<strong> locks (mutexes)</strong> — only one <em>philosopher</em> can hold a <strong>fork </strong>at a time</li><li><strong>Semaphore</strong>: Limits concurrent eaters to 4 (n-1) to prevent deadlock</li><li><strong>States</strong>: Tracks current activity of each philosopher <strong>(THINKING/HUNGRY/EATING)</strong></li></ul><h4><strong>2. Philosopher Lifecycle</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*Ir3JMrNWBN4tou9U" /><figcaption>Each philosopher alternates between thinking and eating</figcaption></figure><h4>3. Thinking Phase</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*hmu3vRIc4jHLIj3h" /></figure><ul><li>Random thinking duration (0.5–1.5 seconds)</li><li>Updates state and prints status</li><li>Accumulates total thinking time</li></ul><h4><strong>4. Eating Phase (Critical Section)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*mWuKE7jl21WotNFV" /></figure><p>Key synchronization elements:</p><ul><li><strong>Semaphore</strong>: Only 4/5 <strong>philosophers </strong>can attempt to eat simultaneously</li><li><strong>Fork Ordering</strong>: Always pick up <strong>lower-ID fork</strong> first to prevent circular wait</li><li><strong>Nested Locks</strong>: Acquire both <strong>forks </strong>atomically</li></ul><h4>5. <strong>Deadlock Prevention</strong></h4><p>Two complementary strategies:</p><ol><li><strong>Semaphore </strong>(n-1): At least one <strong>philosopher </strong>will always be blocked from eating</li><li><strong>Fork </strong>Ordering: Eliminates circular wait condition by establishing a global fork acquisition order</li></ol><h4>6. <strong>State Tracking</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*DMeVHaQgMRXm2fFs" /></figure><ul><li>Provides visibility into system state</li><li>Enables performance monitoring (wait times, meals eaten)</li></ul><h4>7. Solution Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/0*J3z21kBQWq6zGQ1W" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*XaTXt6XVVwYxN6PT" /></figure><h4>How It Works:</h4><h4><strong>1. Limited Concurrent Access :</strong></h4><ul><li>We initialize the <strong>semaphore </strong>to allow at most n-1 <strong>philosophers</strong> (4 out of 5) to attempt eating simultaneously</li><li>This guarantees at least one <strong>philosopher </strong>can always acquire both forks</li></ul><h4>2. Deadlock Prevention</h4><ul><li>The <strong>semaphore</strong> ensures we never reach the dangerous state where all <strong>philosophers </strong>hold one fork</li><li>Combined with <strong>fork </strong>ordering (always picking up lower-numbered fork first), this eliminates circular wait</li></ul><h4>3. Fairness Mechanism</h4><ul><li>The <strong>semaphore’s </strong>FIFO queue ensures <strong>philosophers </strong>get access in the order they requested it</li><li>This prevents any single <strong>philosopher </strong>from being starved indefinitely</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c0b6214b182" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/process-synchronization-simulation-2c0b6214b182">Process Synchronization Simulation</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Concurrency: Simulating Classical Process Synchronization Problems]]></title>
            <link>https://medium.com/operating-system-csci3300/mastering-concurrency-simulating-classical-process-synchronization-problems-1c12dfdd0ebe?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/1c12dfdd0ebe</guid>
            <category><![CDATA[processors]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Ahmad Azfar]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:35:31 GMT</pubDate>
            <atom:updated>2025-05-26T11:35:31.795Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>INTRODUCTION</strong></blockquote><p>Modern operating systems are built to manage many processes running at once like reading data, writing files, managing memory or accessing shared devices that are often in parallel. But with parallelism comes complexity, especially when multiple processes try to access shared resources at the same time. Without proper coordination, this can lead to data inconsistencies, race conditions and even deadlocks.</p><p><strong><em>That’s where process synchronization comes in.</em></strong></p><p>Synchronization is one of the main challenges in parallel programming especially when multiple processes need to access shared resources safely. To explore these challenges, this project simulates three foundation synchronization problems that are commonly used in operating systems.</p><blockquote><strong>PRODUCER-CONSUMER PROBLEM by Siti Aishah (2316920)</strong></blockquote><p>The Producer-Consumer problem is one of the most widely studied synchronization problems in operating systems. It models a common scenario in which two types of processes are producers and consumers.</p><p><strong><em>The two roles:</em></strong></p><ul><li><strong><em>Producers</em></strong><em>:</em> Generate items and place them into shared buffer</li><li><strong><em>Consumers</em></strong><em>:</em> Remove items from the buffer and process them</li></ul><p><strong><em>The main Challenges:</em></strong></p><ul><li>Ensuring that producers don’t overfill the buffer</li><li>Preventing consumers from trying to consume when the buffer is empty</li><li>Making sure the only thread accesses the buffer at a time, to prevent race conditions</li></ul><p><strong><em>How Semaphore are Used:</em></strong></p><p>To handle these challenges, we used three synchronization tools:</p><ol><li><strong>Empty (Counting Semaphore)</strong></li></ol><ul><li>Initialized to the buffer size</li><li>Represent the number of available empty slots</li></ul><p>2.<strong> Full (Counting Semaphore)</strong></p><ul><li>Initialized to 0</li><li>Represents the number of filled slots</li><li>Each consumer must wait full.acquired() before removing item</li></ul><p>3. <strong>Mutex (Binary Lock)</strong></p><ul><li>Ensure mutual exclusion so that only one thread can modify the buffer at a time</li><li>Used by both producers and consumers when accessing the buffer</li></ul><p><strong><em>Producer Flow:</em></strong></p><ol><li>empty.acquire()<strong> </strong>— wait for an empty slot</li><li>mutex.acquire()— lock the buffer</li><li>Add item to buffer</li><li>mutex.release()— unlock the buffer</li><li>full.release()<strong> </strong>— signal that an item is available</li></ol><p><strong><em>Consumer Flow:</em></strong></p><ol><li>full.acquire()— wait for an available item</li><li>mutex.acquire() — lock the buffer</li><li>Remove item buffer</li><li>mutex.re() — unlock the buffer</li><li>empty.release() — signal that space is available</li></ol><p><strong><em>SAMPLE CODE (PYTHON)</em></strong></p><pre>import threading<br>import time<br>import random<br><br># Shared buffer with a fixed size<br>buffer = []<br>BUFFER_SIZE = 5<br><br># Semaphores<br>empty = threading.Semaphore(BUFFER_SIZE)<br>full = threading.Semaphore(0)<br>mutex = threading.Lock()<br><br># Producer thread function<br>def producer(producer_id):<br>    item_id = 1<br>    while item_id &lt;= 5:  # Limit production to 5 per producer<br>        time.sleep(random.uniform(0.5, 1.5))  # Simulate time to produce<br>        empty.acquire()  # Wait if buffer is full<br>        mutex.acquire()  # Enter critical section<br><br>        item = f&quot;Item-{producer_id} - {item_id}&quot;<br>        buffer.append(item)<br>        print(f&quot;[Producer {producer_id}] Produced {item} | Buffer: {buffer}&quot;)<br><br>        mutex.release()  # Exit critical section<br>        full.release()  # Signal that buffer is not empty<br>        item_id += 1<br><br># Consumer thread function<br>def consumer(consumer_id):<br>    consumed_count = 0<br>    while consumed_count &lt; 5:  # Limit consumption to 5 per consumer<br>        time.sleep(random.uniform(1, 2))  # Simulate time to consume<br>        full.acquire()  # Wait if buffer is empty<br>        mutex.acquire()  # Enter critical section<br><br>        item = buffer.pop(0)<br>        print(f&quot;[Consumer {consumer_id}] Consumed {item} | Buffer: {buffer}&quot;)<br><br>        mutex.release()  # Exit critical section<br>        empty.release()  # Signal that buffer has space<br>        consumed_count += 1<br><br># Create and start threads<br>producers = [threading.Thread(target=producer, args=(i,)) for i in range(1, 3)]<br>consumers = [threading.Thread(target=consumer, args=(i,)) for i in range(1, 3)]<br><br>for p in producers:<br>    p.start()<br><br>for c in consumers:<br>    c.start()<br><br>for p in producers:<br>    p.join()<br><br>for c in consumers:<br>    c.join()</pre><p><strong><em>OUTPUT</em></strong></p><pre>[Producer 1] Produced Item-1 - 1 | Buffer: [&#39;Item-1 - 1&#39;]<br>[Producer 2] Produced Item-2 - 1 | Buffer: [&#39;Item-1 - 1&#39;, &#39;Item-2 - 1&#39;]<br>[Consumer 2] Consumed Item-1 - 1 | Buffer: [&#39;Item-2 - 1&#39;]<br>[Producer 1] Produced Item-1 - 2 | Buffer: [&#39;Item-2 - 1&#39;, &#39;Item-1 - 2&#39;]<br>[Consumer 1] Consumed Item-2 - 1 | Buffer: [&#39;Item-1 - 2&#39;]<br>[Producer 2] Produced Item-2 - 2 | Buffer: [&#39;Item-1 - 2&#39;, &#39;Item-2 - 2&#39;]<br>[Consumer 2] Consumed Item-1 - 2 | Buffer: [&#39;Item-2 - 2&#39;]<br>[Producer 1] Produced Item-1 - 3 | Buffer: [&#39;Item-2 - 2&#39;, &#39;Item-1 - 3&#39;]<br>[Consumer 1] Consumed Item-2 - 2 | Buffer: [&#39;Item-1 - 3&#39;]<br>[Producer 2] Produced Item-2 - 3 | Buffer: [&#39;Item-1 - 3&#39;, &#39;Item-2 - 3&#39;]<br>[Producer 1] Produced Item-1 - 4 | Buffer: [&#39;Item-1 - 3&#39;, &#39;Item-2 - 3&#39;, &#39;Item-1 - 4&#39;]<br>[Consumer 2] Consumed Item-1 - 3 | Buffer: [&#39;Item-2 - 3&#39;, &#39;Item-1 - 4&#39;]<br>[Producer 1] Produced Item-1 - 5 | Buffer: [&#39;Item-2 - 3&#39;, &#39;Item-1 - 4&#39;, &#39;Item-1 - 5&#39;]<br>[Producer 2] Produced Item-2 - 4 | Buffer: [&#39;Item-2 - 3&#39;, &#39;Item-1 - 4&#39;, &#39;Item-1 - 5&#39;, &#39;Item-2 - 4&#39;]<br>[Consumer 1] Consumed Item-2 - 3 | Buffer: [&#39;Item-1 - 4&#39;, &#39;Item-1 - 5&#39;, &#39;Item-2 - 4&#39;]<br>[Producer 2] Produced Item-2 - 5 | Buffer: [&#39;Item-1 - 4&#39;, &#39;Item-1 - 5&#39;, &#39;Item-2 - 4&#39;, &#39;Item-2 - 5&#39;]<br>[Consumer 2] Consumed Item-1 - 4 | Buffer: [&#39;Item-1 - 5&#39;, &#39;Item-2 - 4&#39;, &#39;Item-2 - 5&#39;]<br>[Consumer 1] Consumed Item-1 - 5 | Buffer: [&#39;Item-2 - 4&#39;, &#39;Item-2 - 5&#39;]<br>[Consumer 2] Consumed Item-2 - 4 | Buffer: [&#39;Item-2 - 5&#39;]<br>[Consumer 1] Consumed Item-2 - 5 | Buffer: []</pre><blockquote><strong>READERS-WRITERS PROBLEM by Muhammad Amirul Haziq (2319959)</strong></blockquote><p>The Readers-Writers Problem is a classic synchronization issue in operating systems where multiple reader and writer processes share a common resource (e.g., a file or database).</p><p><strong><em>Two roles:</em></strong></p><ul><li>Readers: read concurrently with other readers, and must wait if a writer is writing.</li><li>Writers: Needs exclusive access to shared resources but must wait until all readers have finished and other writers are active.</li></ul><p><strong><em>Main challenges:</em></strong></p><ul><li>Readers can access the resource simultaneously.</li><li>Writers must have exclusive abscess.</li><li>No data inconsistency, race conditions, deadlocks.</li><li>No starvation.</li></ul><p><strong><em>Tools utilized to get solution:</em></strong></p><ol><li>resource_access</li></ol><p>resource_access is a binary semaphore, it controls access to shared resources, acquired by writers before writing, acquired by the first reader, and the last reader releases it.</p><p>2. read_count_lock</p><p>read_count_lock is a Mutex/lock that ensures mutual exclusion when modifying read_count, it tracks the number of active readers and prevents conditions when multiple readers arrive or leave at the same time.</p><p><strong>The code should be understood as having two flows, the reader and writer flow. Each flow has 4 phases.</strong></p><p>For the reader flow, first it has a Thinking Phase which simulates delay using time.sleep() to represent some work before accessing the resource. Next, the Waiting Phase is when the reader prepares to enter the critical section. It increments the read_count in a mutex_protected block. If this is the first reader, the resource_access semaphore is locked in order to block writers. Moving on to the most critical section, Reading Phase, when multiple readers can read simultaneously. The critical section is simulated via simulate_critical_section(). Lastly, the Exit phase decrements read_count, if it is the last reader it will release resource_access to allow writers to proceed.</p><p>On the other hand, the writer flow also has the same 4 phases. For the thinking phase, it simulates time taken to prepare data. The waiting phase is when the writer waits to acquire resource_access, to ensure exclusive access. Equally important, the writing phase(critical section) performs writing where no other reader or writer can access. This critical section is simulated via simulate_critical_section(). The exit phase involves the release of resource_access, allowing other readers or writers to proceed.</p><p>The code can prevent common issues such as race conditions, data corruption, starvation and deadlocks. Race condition is prevented by protecting read_count with a mutex(read_count_lock) that prevents incorrect concurrent modifications. Data corruption is avoided by ensuring that only one writer or multiple readers can access the resource at a time. This is by giving writers exclusive access using a binary semaphore(resource access). Lastly, the logic ensures that once all readers finish, the writer can proceed by using reader_priority solution in order to starve writers. This reader-priority solution allows multiple readers to access the resource concurrently, giving exclusive access to writers, using semaphores and locks to effectively maintain synchronization and data consistency.</p><p><strong><em>SAMPLE CODE (PYTHON)</em></strong></p><pre>import threading<br>import time<br>import random<br><br># Semaphores and shared variables<br>read_count = 0<br>read_count_lock = threading.Lock()     # Protects read_count<br>resource_access = threading.Semaphore(1)  # Controls access to the shared resource<br><br># Simulation of critical section<br>def simulate_critical_section(action, id):<br>    print(f&quot;[{action}] Process-{id} is in the critical section.&quot;)<br>    time.sleep(random.uniform(0.5, 1.5))<br>    print(f&quot;[{action}] Process-{id} is exiting the critical section.&quot;)<br><br># Reader thread function<br>def reader(id):<br>    global read_count<br>    while True:<br>        print(f&quot;[Reader-{id}] Thinking...&quot;)<br>        time.sleep(random.uniform(0.5, 1.0))  # Simulate thinking<br><br>        print(f&quot;[Reader-{id}] Waiting to read...&quot;)<br>        with read_count_lock:<br>            read_count += 1<br>            if read_count == 1:<br>                print(f&quot;[Reader-{id}] First reader, locking resource.&quot;)<br>                resource_access.acquire()<br>        print(f&quot;[Reader-{id}] Reading now.&quot;)<br><br>        simulate_critical_section(&quot;READ&quot;, id)<br><br>        with read_count_lock:<br>            read_count -= 1<br>            if read_count == 0:<br>                print(f&quot;[Reader-{id}] Last reader, unlocking resource.&quot;)<br>                resource_access.release()<br>        print(f&quot;[Reader-{id}] Finished reading.\n&quot;)<br><br>        time.sleep(random.uniform(1, 2))  # Rest before next read<br><br># Writer thread function<br>def writer(id):<br>    while True:<br>        print(f&quot;[Writer-{id}] Thinking...&quot;)<br>        time.sleep(random.uniform(1, 2))  # Simulate thinking<br><br>        print(f&quot;[Writer-{id}] Waiting to write...&quot;)<br>        resource_access.acquire()<br>        print(f&quot;[Writer-{id}] Writing now.&quot;)<br><br>        simulate_critical_section(&quot;WRITE&quot;, id)<br><br>        resource_access.release()<br>        print(f&quot;[Writer-{id}] Finished writing.\n&quot;)<br><br>        time.sleep(random.uniform(1, 2))  # Rest before next write<br><br># Create and start reader and writer threads<br>reader_threads = [threading.Thread(target=reader, args=(i,)) for i in range(3)]<br>writer_threads = [threading.Thread(target=writer, args=(i,)) for i in range(2)]<br><br>for t in reader_threads + writer_threads:<br>    t.daemon = True  # Allow program to exit even if threads are running<br>    t.start()<br><br># Run simulation for a fixed time<br>simulation_time = 20  # seconds<br>time.sleep(simulation_time)<br>print(&quot;Simulation ended.&quot;)</pre><p><strong><em>OUTPUT</em></strong></p><pre>[Reader-0] Thinking...<br>[Reader-1] Thinking...<br>[Reader-2] Thinking...<br>[Writer-0] Thinking...<br>[Writer-1] Thinking...<br>[Reader-1] Waiting to read...<br>[Reader-1] First reader, locking resource.<br>[Reader-1] Reading now.<br>[READ] Process-1 is in the critical section.<br>[Reader-0] Waiting to read...<br>[Reader-0] Reading now.<br>[READ] Process-0 is in the critical section.<br>[Reader-2] Waiting to read...<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[READ] Process-1 is exiting the critical section.<br>[Reader-1] Finished reading.<br><br>[Writer-1] Waiting to write...<br>[READ] Process-0 is exiting the critical section.<br>[Reader-0] Finished reading.<br><br>[Writer-0] Waiting to write...<br>[READ] Process-2 is exiting the critical section.<br>[Reader-2] Last reader, unlocking resource.<br>[Reader-2] Finished reading.<br><br>[Writer-1] Writing now.<br>[WRITE] Process-1 is in the critical section.<br>[Reader-0] Thinking...<br>[Reader-1] Thinking...<br>[WRITE] Process-1 is exiting the critical section.<br>[Writer-1] Finished writing.<br><br>[Writer-0] Writing now.<br>[WRITE] Process-0 is in the critical section.<br>[Reader-0] Waiting to read...<br>[Reader-0] First reader, locking resource.<br>[Reader-1] Waiting to read...<br>[WRITE] Process-0 is exiting the critical section.<br>[Writer-0] Finished writing.<br><br>[Reader-0] Reading now.<br>[READ] Process-0 is in the critical section.<br>[Reader-1] Reading now.<br>[READ] Process-1 is in the critical section.<br>[Reader-2] Thinking...<br>[READ] Process-0 is exiting the critical section.<br>[Reader-0] Finished reading.<br><br>[READ] Process-1 is exiting the critical section.<br>[Reader-1] Last reader, unlocking resource.<br>[Reader-1] Finished reading.<br><br>[Reader-2] Waiting to read...<br>[Reader-2] First reader, locking resource.<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[Writer-0] Thinking...<br>[Writer-1] Thinking...<br>[Reader-1] Thinking...<br>[READ] Process-2 is exiting the critical section.<br>[Reader-2] Last reader, unlocking resource.<br>[Reader-2] Finished reading.<br><br>[Reader-0] Thinking...<br>[Writer-0] Waiting to write...<br>[Writer-0] Writing now.<br>[WRITE] Process-0 is in the critical section.<br>[Reader-1] Waiting to read...<br>[Reader-1] First reader, locking resource.<br>[Reader-0] Waiting to read...<br>[Reader-2] Thinking...<br>[Writer-1] Waiting to write...<br>[WRITE] Process-0 is exiting the critical section.<br>[Writer-0] Finished writing.<br><br>[Reader-1] Reading now.<br>[READ] Process-1 is in the critical section.<br>[Reader-0] Reading now.<br>[READ] Process-0 is in the critical section.<br>[Reader-2] Waiting to read...<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[READ] Process-0 is exiting the critical section.<br>[Reader-0] Finished reading.<br><br>[READ] Process-1 is exiting the critical section.<br>[Reader-1] Finished reading.<br><br>[READ] Process-2 is exiting the critical section.<br>[Reader-2] Last reader, unlocking resource.<br>[Reader-2] Finished reading.<br><br>[Writer-1] Writing now.<br>[WRITE] Process-1 is in the critical section.<br>[Writer-0] Thinking...<br>[Reader-0] Thinking...<br>[WRITE] Process-1 is exiting the critical section.<br>[Writer-1] Finished writing.<br><br>[Writer-0] Waiting to write...<br>[Writer-0] Writing now.<br>[WRITE] Process-0 is in the critical section.<br>[Reader-1] Thinking...<br>[Reader-2] Thinking...<br>[Reader-0] Waiting to read...<br>[Reader-0] First reader, locking resource.<br>[WRITE] Process-0 is exiting the critical section.<br>[Writer-0] Finished writing.<br><br>[Reader-0] Reading now.<br>[READ] Process-0 is in the critical section.<br>[Reader-2] Waiting to read...<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[Writer-1] Thinking...<br>[Reader-1] Waiting to read...<br>[Reader-1] Reading now.<br>[READ] Process-1 is in the critical section.<br>[READ] Process-0 is exiting the critical section.<br>[Reader-0] Finished reading.<br><br>[Writer-0] Thinking...<br>[READ] Process-1 is exiting the critical section.<br>[Reader-1] Finished reading.<br><br>[READ] Process-2 is exiting the critical section.<br>[Reader-2] Last reader, unlocking resource.<br>[Reader-2] Finished reading.<br><br>[Reader-0] Thinking...<br>[Writer-1] Waiting to write...<br>[Writer-1] Writing now.<br>[WRITE] Process-1 is in the critical section.<br>[Reader-0] Waiting to read...<br>[Reader-0] First reader, locking resource.<br>[Writer-0] Waiting to write...<br>[Reader-1] Thinking...<br>[WRITE] Process-1 is exiting the critical section.<br>[Writer-1] Finished writing.<br><br>[Reader-0] Reading now.<br>[READ] Process-0 is in the critical section.<br>[Reader-2] Thinking...<br>[Reader-1] Waiting to read...<br>[Reader-1] Reading now.<br>[READ] Process-1 is in the critical section.<br>[Reader-2] Waiting to read...<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[READ] Process-0 is exiting the critical section.<br>[Reader-0] Finished reading.<br><br>[Writer-1] Thinking...<br>[READ] Process-2 is exiting the critical section.<br>[Reader-2] Finished reading.<br><br>[READ] Process-1 is exiting the critical section.<br>[Reader-1] Last reader, unlocking resource.<br>[Reader-1] Finished reading.<br><br>[Writer-0] Writing now.<br>[WRITE] Process-0 is in the critical section.<br>[Writer-1] Waiting to write...<br>[WRITE] Process-0 is exiting the critical section.<br>[Writer-0] Finished writing.<br><br>[Writer-1] Writing now.<br>[WRITE] Process-1 is in the critical section.<br>[Reader-1] Thinking...<br>[Reader-2] Thinking...<br>[Reader-0] Thinking...<br>[WRITE] Process-1 is exiting the critical section.<br>[Writer-1] Finished writing.<br><br>[Reader-1] Waiting to read...<br>[Reader-1] First reader, locking resource.<br>[Reader-1] Reading now.<br>[READ] Process-1 is in the critical section.<br>[Reader-0] Waiting to read...<br>[Reader-0] Reading now.<br>[READ] Process-0 is in the critical section.<br>[Reader-2] Waiting to read...<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[Writer-0] Thinking...<br>[READ] Process-0 is exiting the critical section.<br>[Reader-0] Finished reading.<br><br>[READ] Process-2 is exiting the critical section.<br>[Reader-2] Finished reading.<br><br>[READ] Process-1 is exiting the critical section.<br>[Reader-1] Last reader, unlocking resource.<br>[Reader-1] Finished reading.<br><br>[Writer-1] Thinking...<br>[Writer-0] Waiting to write...<br>[Writer-0] Writing now.<br>[WRITE] Process-0 is in the critical section.<br>[Reader-2] Thinking...<br>[Reader-0] Thinking...<br>[WRITE] Process-0 is exiting the critical section.<br>[Writer-0] Finished writing.<br><br>[Reader-2] Waiting to read...<br>[Reader-2] First reader, locking resource.<br>[Reader-2] Reading now.<br>[READ] Process-2 is in the critical section.<br>[Writer-1] Waiting to write...<br>[Reader-1] Thinking...<br>Simulation ended.</pre><blockquote><strong>DINING PHILOSOPHERS PROBLEM by Ahmad Azfar (2319457) &amp; Muhammad Nazhim (2315419)</strong></blockquote><p>The Dining Philosophers Problem is also a synchronization problem in operating systems and concurrent programming. It illustrates the challenges of allocating limited resources (e.g., forks) among multiple competing processes (e.g., philosophers) without causing deadlock or starvation.</p><p><strong><em>Role (5 Philosophers):</em></strong></p><ul><li>Each philosopher alternates between thinking and eating.</li><li>To eat, a philosopher must acquire two forks, one on each side.</li><li>Forks are shared with neighbors; hence, careful coordination is needed.</li></ul><p><strong><em>Main Challenges:</em></strong></p><ul><li><strong>Mutual exclusion:</strong> A fork can only be used by one philosopher at a time.</li><li><strong>Deadlock prevention:</strong> Avoid situations where every philosopher is waiting for a fork.</li><li><strong>Starvation avoidance:</strong> Ensure all philosophers eventually get a chance to eat.</li><li><strong>Concurrency:</strong> Maximize the number of philosophers eating concurrently.</li></ul><p>In our implementation, we simulate five philosophers who alternate between <strong>thinking</strong> and <strong>eating</strong>. Each philosopher requires two forks (shared resources) to eat: one on the left and one on the right. Semaphores are used to manage the access to these forks, ensuring mutual exclusion and preventing deadlocks.</p><p><strong><em>Tools utilized to get solution:</em></strong></p><ol><li>mutex</li></ol><ul><li>A binary semaphore (threading.Semaphore(1)) used to enforce mutual exclusion while accessing/modifying shared data structures like state[].</li><li>Ensures that only one philosopher at a time can change the state or test neighbors.</li></ul><p>2. semaphores[]</p><ul><li>An array of semaphores, one for each philosopher.</li><li>Each semaphore acts as a personal lock for a philosopher.</li><li>A philosopher waits (acquire) on their own semaphore when hungry and is only signaled (release) when it’s safe to eat.</li></ul><p>3. state[]</p><ul><li>An array tracking the current state of each philosopher: THINKING, HUNGRY, or EATING.</li><li>Used to determine when a philosopher is allowed to pick up forks and eat.</li></ul><p>4. test(i) Funtion</p><ul><li>A logic function that checks whether philosopher i can start eating based on the states of their neighbors.</li><li>If neighbors are not eating, sets state[i] = EATING and releases their semaphore.</li></ul><p>5. left(i) and right(i) Funtions</p><ul><li>Utility functions to identify the indices of a philosopher’s neighboring philosophers.</li></ul><p><strong><em>SAMPLE CODE (PYTHON)</em></strong></p><pre>import threading<br>import time<br>import random<br><br>#Number of philosophers<br>N = 5<br><br>#States<br>THINKING = 0<br>HUNGRY = 1<br>EATING = 2<br><br>#Semaphore for each philosopher<br>state = [THINKING] * N<br>semaphores = [threading.Semaphore(0) for _ in range(N)]<br>mutex = threading.Semaphore(1)<br><br>def left(i):<br>    return (i + N - 1) % N<br><br>def right(i):<br>    return (i + 1) % N<br><br>def test(i):<br>    #Check if philosopher i can eat<br>    if state[i] == HUNGRY and state[left(i)] != EATING and state[right(i)] != EATING:<br>        state[i] = EATING<br>        print(f&quot;Philosopher {i} starts EATING&quot;)<br>        semaphores[i].release()<br>def take_forks(i):<br>    mutex.acquire()<br>    state[i] = HUNGRY<br>    print(f&quot;Philosopher {i} is HUNGRY&quot;)<br>    test(i)<br>    mutex.release()<br>    semaphores[i].acquire()<br><br>def put_forks(i):<br>    mutex.acquire()<br>    state[i] = THINKING<br>    print(f&quot;Philosopher {i} puts down forks and starts THINKING&quot;)<br>    test(left(i))<br>    test(right(i))<br>    mutex.release()<br><br>def philosopher(i):<br>    while True:<br>        print(f&quot;Philosopher {i} is THINKING&quot;)<br>        time.sleep(random.uniform(1, 3))  #Thinking<br>        take_forks(i)<br>        print(f&quot;Philosopher {i} is EATING&quot;)<br>        time.sleep(random.uniform(1, 2))  #Eating<br>        put_forks(i)<br><br><br>#Create and start philosopher threads<br>threads = []<br>for i in range(N):<br>    t = threading.Thread(target=philosopher, args=(i,))<br>    threads.append(t)<br>    t.start()<br><br>#Let simulation run for a certain time<br>time.sleep(30)</pre><p><strong><em>OUTPUT</em></strong></p><pre>Philosopher 0 is HUNGRY<br>Philosopher 1 puts down forks and starts THINKING<br>Philosopher 2 starts EATING<br>Philosopher 1 is THINKING<br>Philosopher 2 is EATING<br>Philosopher 0 has finished EATING and put down forks.<br>Philosopher 0 is THINKING.<br>Philosopher 0 is EATING.<br>Philosopher 4 is trying to pick up forks.<br>Philosopher 3 has finished EATING and put down forks.<br>Philosopher 3 is THINKING.<br>Philosopher 2 is EATING.<br>Philosopher 4 is trying to pick up forks.<br>Philosopher 0 is THINKING<br>Philosopher 1 is THINKING<br>Philosopher 2 is THINKING<br>Philosopher 3 is THINKING<br>Philosopher 4 is THINKING<br>Philosopher 3 is HUNGRY<br>Philosopher 4 puts down forks and starts THINKING<br>Philosopher 0 starts EATING<br>Philosopher 4 is THINKING<br>Philosopher 0 is EATING<br>Philosopher 2 puts down forks and starts THINKING<br>Philosopher 3 starts EATING<br>Philosopher 2 is THINKING<br>Philosopher 3 is EATING.<br>Philosopher 0 has finished EATING and put down forks.<br>Philosopher 0 is THINKING.<br>Philosopher 4 is EATING.<br>Philosopher 3 is trying to pick up forks.<br>Philosopher 4 is HUNGRY<br>Philosopher 2 is HUNGRY<br>Philosopher 2 has finished EATING and put down forks.<br>Philosopher 2 is THINKING.<br>Philosopher 2 is trying to pick up forks.<br>Philosopher 1 is HUNGRY<br>Philosopher 0 puts down forks and starts THINKING<br>Philosopher 1 starts EATING<br>Philosopher 0 is THINKING<br>Philosopher 1 is EATING<br>Philosopher 3 is HUNGRY<br>Philosopher 3 starts EATING<br>Philosopher 3 is EATING<br>Philosopher 4 has finished EATING and put down forks.Philosopher 4 is EATING.</pre><p><strong><em>CONCLUSION</em></strong></p><p>In conclusion, the <strong>Producer-Consumer</strong>, <strong>Readers-Writers</strong>, and <strong>Dining Philosophers</strong> problems are foundational synchronization challenges in operating systems that highlight the importance of coordinating access to shared resources. Each problem emphasizes different aspects of concurrency such as buffer management, read/write access control, and resource allocation while sharing common goals: ensuring mutual exclusion, preventing race conditions, avoiding deadlocks, and eliminating starvation. Solving these problems requires careful use of synchronization tools like semaphores, mutexes, and condition variables, forming the basis for designing safe and efficient concurrent systems.</p><blockquote><strong>Written by Ahmad Azfar (2319457), Siti Aishah (2316920), Muhammad Nazhim (2315419), and Muhammad Amirul Haziq (2319959)</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c12dfdd0ebe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/mastering-concurrency-simulating-classical-process-synchronization-problems-1c12dfdd0ebe">Mastering Concurrency: Simulating Classical Process Synchronization Problems</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process Synchronization Simulation by Group 3 Section 6]]></title>
            <link>https://medium.com/operating-system-csci3300/process-synchronization-simulation-by-group-3-section-6-2115a8e996c0?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/2115a8e996c0</guid>
            <dc:creator><![CDATA[Adam Muhaimin]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:35:10 GMT</pubDate>
            <atom:updated>2025-05-26T11:35:10.742Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Provided by: Mohammed Aman Ashraf<strong><br></strong>Process synchronization is a fundamental aspect of operating systems, playing a vital role in managing how multiple processes or threads interact when accessing shared resources. In multi-processing environments, processes often execute concurrently, leading to potential issues such as race conditions, deadlocks, and data inconsistencies if synchronization mechanisms are not properly implemented. This report focuses on three classical problems used to study and understand synchronization: the Producer-Consumer, Readers-Writers, and Dining Philosophers problems. Each of these models highlights different challenges that arise in concurrent systems and serves as a foundation for building reliable multi-threaded applications.</p><p>The Producer-Consumer problem involves two types of processes: producers, which generate data and insert it into a shared buffer, and consumers, which remove data from the buffer for processing. The main challenge lies in ensuring that the producer does not add data when the buffer is full and that the consumer does not attempt to remove data from an empty buffer. This requires the use of synchronization tools such as semaphores or mutexes to control access to the buffer and coordinate the timing between producers and consumers. In the simulation presented, real-time output visualization is provided to demonstrate the status of the buffer and the activity of each process.</p><p>The Readers-Writers problem presents a scenario where a shared resource, such as a database, is accessed by multiple processes categorized as readers or writers. While multiple readers can access the resource concurrently, writers require exclusive access to prevent conflicts and maintain data consistency. A key challenge is to avoid both writer starvation (where writers wait indefinitely) and reader starvation (where readers are blocked too frequently). The solution implemented in this report ensures balanced access through semaphore-based synchronization, allowing fair and efficient handling of concurrent read and write operations.</p><p>The Dining Philosophers problem models a situation where a number of processes (philosophers) compete for a limited set of shared resources (chopsticks). This problem is a classic example of how poor resource management can lead to deadlock, where all philosophers are waiting indefinitely for resources. The simulation addresses this issue by implementing a semaphore-based protocol that prevents circular wait conditions and ensures that each philosopher can eat without falling into starvation or deadlock scenarios.</p><p>Through the implementation and analysis of these problems, this report aims to provide a deeper understanding of synchronization principles and the effective use of semaphores in managing concurrent process execution.</p><h3>Producer-Consumer Problem Simulation with Semaphores in C</h3><p>Provided by: Muhamad Adam Muhaimin bin Shahbani</p><p>In this article, we will discuss the Producer-Consumer problem and demonstrate the simulation that uses semaphores to manage the access to a shared buffer. Multiple producers and consumers are operating simultaneously in this problem which is a classic example of process synchronization in operating systems. We must make sure that producers do not overflow the buffer and that consumers do not try to consume from an empty buffer. To help you grasp the system’s operation, we will also show you a buffer visualization.</p><h3>Understanding the Producer-Consumer Problem</h3><p>The Producer-Consumer problem involves two types of processes:</p><ol><li><strong>Producers</strong>: These processes generate data and add it to a shared buffer.</li><li><strong>Consumers</strong>: These processes retrieve and process data from the buffer.</li></ol><p>However, the shared buffer has a limited size and we need to synchronize the producer and consumer processes to ensure that:</p><ul><li>A producer waits if the buffer is full.</li><li>A consumer waits if the buffer is empty.</li></ul><p>The challenge is to manage access to the buffer so that there are no race conditions, deadlocks, or starvation while ensuring efficient synchronization.</p><h3>Problem Setup and Synchronization with Semaphores</h3><p>In this simulation, we use semaphores for synchronization:</p><ul><li><strong>empty</strong>: A counting semaphore that tracks the number of empty slots in the buffer. Initially, all buffer slots are empty.</li><li><strong>full</strong>: A counting semaphore that tracks the number of full slots in the buffer. Initially, no items are in the buffer.</li><li><strong>mutex</strong>: A binary semaphore used to implement mutual exclusion when accessing the buffer to prevent race conditions.</li></ul><h3>How Semaphores Work:</h3><ul><li>Producer: The producer waits for an empty slot (empty semaphore) and acquires the mutex to safely add an item to the buffer. After producing, it increments the full semaphore to signal that a new item is available.</li><li>Consumer: The consumer waits for a full slot (full semaphore) and acquires the mutex to safely consume an item from the buffer. After consuming, it increments the empty semaphore to signal that a slot is now empty.</li></ul><p>This ensures synchronization between the producer and consumer processes and prevent conflicts and allows them to work in harmony.</p><h3>Buffer Visualization</h3><p>To help visualize the simulation, we implemented a function that displays the current state of the buffer. This allows us to see the buffer contents in real-time as producers and consumers operate on it.</p><ul><li>Empty slots are represented by -1 and the filled slots show the items produced by the producer and consumed by the consumer.</li><li>The output is updated every time an item is produced or consumed, showing the buffer’s state as an array of integers.</li></ul><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;pthread.h&gt;<br>#include &lt;semaphore.h&gt;<br>#include &lt;unistd.h&gt;<br><br>#define MAX_BUFFER_SIZE 5 // Maximum size of the buffer<br>#define NUM_PRODUCERS 2   // Number of producers<br>#define NUM_CONSUMERS 2   // Number of consumers<br><br>// Shared buffer<br>int buffer[MAX_BUFFER_SIZE];<br>int in = 0;  // index for next item to produce<br>int out = 0; // index for next item to consume<br><br>// Semaphores for synchronization<br>sem_t empty;  // Semaphore to count empty slots in the buffer<br>sem_t full;   // Semaphore to count full slots in the buffer<br>sem_t mutex;  // Semaphore to ensure mutual exclusion while accessing buffer<br><br>// Function to display the current state of the buffer<br>void display_buffer() {<br>    printf(&quot;Buffer: [ &quot;);<br>    for (int i = 0; i &lt; MAX_BUFFER_SIZE; i++) {<br>        if (buffer[i] == -1)<br>            printf(&quot;  , &quot;);<br>        else<br>            printf(&quot;%2d, &quot;, buffer[i]);<br>    }<br>    printf(&quot;]\n&quot;);<br>}<br><br>// Producer thread function<br>void* producer(void* arg) {<br>    while(1) {<br>        int item = rand() % 100; // produce a random item<br>        sem_wait(&amp;empty); // Decrement empty slots<br>        sem_wait(&amp;mutex); // Enter critical section<br>        <br>        // Add item to the buffer<br>        buffer[in] = item;<br>        printf(&quot;Producer produced: %d at index %d\n&quot;, item, in);<br>        in = (in + 1) % MAX_BUFFER_SIZE; // Move to next slot<br>        <br>        // Display the current state of the buffer<br>        display_buffer();<br>        <br>        sem_post(&amp;mutex); // Exit critical section<br>        sem_post(&amp;full);  // Increment full slots<br>        <br>        sleep(rand() % 2); // Simulate production time<br>    }<br>    return NULL;<br>}<br><br>// Consumer thread function<br>void* consumer(void* arg) {<br>    while(1) {<br>        sem_wait(&amp;full);  // Decrement full slots<br>        sem_wait(&amp;mutex); // Enter critical section<br>        <br>        // Consume item from the buffer<br>        int item = buffer[out];<br>        buffer[out] = -1; // Mark the slot as empty<br>        printf(&quot;Consumer consumed: %d from index %d\n&quot;, item, out);<br>        out = (out + 1) % MAX_BUFFER_SIZE; // Move to next slot<br>        <br>        // Display the current state of the buffer<br>        display_buffer();<br>        <br>        sem_post(&amp;mutex); // Exit critical section<br>        sem_post(&amp;empty);  // Increment empty slots<br>        <br>        sleep(rand() % 2); // Simulate consumption time<br>    }<br>    return NULL;<br>}<br><br>int main() {<br>    pthread_t producers[NUM_PRODUCERS], consumers[NUM_CONSUMERS];<br>    <br>    // Initialize semaphores<br>    sem_init(&amp;empty, 0, MAX_BUFFER_SIZE); // Initially, the buffer is empty<br>    sem_init(&amp;full, 0, 0);  // Initially, no items in the buffer<br>    sem_init(&amp;mutex, 0, 1); // Binary semaphore for mutual exclusion<br><br>    // Initialize the buffer slots to be empty (-1)<br>    for (int i = 0; i &lt; MAX_BUFFER_SIZE; i++) {<br>        buffer[i] = -1; // Empty slots represented by -1<br>    }<br><br>    // Create producer threads<br>    for (int i = 0; i &lt; NUM_PRODUCERS; i++) {<br>        pthread_create(&amp;producers[i], NULL, producer, NULL);<br>    }<br><br>    // Create consumer threads<br>    for (int i = 0; i &lt; NUM_CONSUMERS; i++) {<br>        pthread_create(&amp;consumers[i], NULL, consumer, NULL);<br>    }<br><br>    // Wait for threads to finish (in this case, they run indefinitely)<br>    for (int i = 0; i &lt; NUM_PRODUCERS; i++) {<br>        pthread_join(producers[i], NULL);<br>    }<br>    for (int i = 0; i &lt; NUM_CONSUMERS; i++) {<br>        pthread_join(consumers[i], NULL);<br>    }<br><br>    // Clean up semaphores (in practice, these lines are never reached)<br>    sem_destroy(&amp;empty);<br>    sem_destroy(&amp;full);<br>    sem_destroy(&amp;mutex);<br><br>    return 0;<br>}</pre><h3>Explanation:</h3><ul><li><strong>Buffer Display</strong>: The display_buffer() function prints the current contents of the buffer, with empty slots represented as -1.</li><li><strong>Producers and Consumers</strong>: Producer threads add random items to the buffer and consumer threads remove items from it. The semaphores ensure that no producer attempts to add an item when the buffer is full, and no consumer attempts to consume when the buffer is empty.</li></ul><p>The buffer’s state is printed to the console after each item is produced or consumed, providing a clear, real-time view of the system’s state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*WHjar6nXcDEMA2qS" /><figcaption>Screenshot of the buffer state after multiple producer and consumer operations.</figcaption></figure><h3>Readers-Writers Problem Simulation with Semaphores in Python</h3><p>Provided by: Muhammad Haziq Zulhazmi bin Hairul Nizam</p><p>Next we’ll discuss the Readers-Writers problem and demonstrate the simulation that uses semaphores to solve the problem. Readers-Writers problem is a classic synchronization challenge where multiple processes (readers and writers) access a shared resource, such as a database or file. The core issue is ensuring that:</p><ul><li><strong>Readers</strong> can read concurrently (no mutual exclusion required).</li><li><strong>Writers</strong> require exclusive access (no other reader/writer can access the resource during writing).</li><li>Avoid starvation of either readers or writers.</li></ul><p>This problem highlights the need for thread-safe resource management to prevent data corruption or inconsistent states.</p><p><strong>Solution Using Semaphores</strong></p><p>Semaphores coordinate access to the shared resource:</p><ul><li><strong>Readcount</strong>: Tracks the number of active readers.</li><li><strong>Mutex</strong>: A binary semaphore to protect read_count.</li><li><strong>Resources</strong>: A semaphore ensuring exclusive access for writers or the first/last reader.</li></ul><p><strong>Workflow</strong>:</p><ol><li><strong>Reader</strong>:</li></ol><ul><li>Acquire mutex to update readcount.</li><li>If the reader is the first, acquire resources to block writers.</li><li>Release mutex and read.</li><li>After reading, re-acquire mutex to decrement readcount.</li><li>If the reader is the last, release the resource.</li></ul><p><strong>2. Writer</strong>:</p><ul><li>Acquire resources to block all other threads.</li><li>Write to the resource.</li><li>Release resource.</li></ul><p>This implementation prioritizes readers (new readers can enter while a writer is waiting).</p><h3>Solving readers-writers problem in Visualization</h3><p>This Python script simulates the <strong>Readers-Writers problem</strong> using threads and semaphores to manage concurrent access to a shared resource</p><p><strong>Key Components</strong>:</p><ol><li><strong>Semaphores</strong>:</li></ol><ul><li><strong>mutex</strong>: Protects the readcount variable (ensures only one thread updates it at a time).</li><li><strong>resource</strong>: Controls exclusive access for writers or the first/last reader.</li></ul><p>2. <strong>Global Variables</strong>:</p><ul><li><strong>readcount</strong>: Tracks the number of active readers.</li></ul><p><strong>3. Functions</strong>:</p><p>reader(id):</p><ul><li>Waits, acquires mutex to increment readcount.</li><li>If it’s the <strong>first reader</strong>, it acquires resources (blocking writers).</li><li>Releases mutex, reads the resource, then decrements readcount on exit.</li><li>If it’s the <strong>last reader</strong>, it releases resources.</li></ul><p>writer(id):</p><ul><li>Waits, acquires resources (blocking all other threads).</li><li>Writes to the resource, then releases the resource.</li></ul><p><strong>4. Thread Creation</strong>:</p><ul><li>Launches 3 readers and 3 writers with staggered start times (time.sleep()).</li></ul><pre>import threading<br>import time<br><br># Semaphores and shared variables<br>read_count = 0<br>mutex = threading.Semaphore(1)    # Protects read_count<br>resource = threading.Semaphore(1) # Controls resource access<br><br>def reader(id):<br>    global read_count<br>    time.sleep(0.5 * id)  # Simulate staggered starts<br>    <br>    print(f&quot;Reader {id}: WAITING to read&quot;)<br>    with mutex:<br>        read_count += 1<br>        if read_count == 1:<br>            resource.acquire()<br>    print(f&quot;Reader {id}: READING&quot;)<br><br>    time.sleep(2)  # Simulate reading time<br>    <br>    with mutex:<br>        read_count -= 1<br>        if read_count == 0:<br>            resource.release()<br>    print(f&quot;Reader {id}: FINISHED reading&quot;)<br><br>def writer(id):<br>    time.sleep(0.5 * id)  # Simulate staggered starts<br>    <br>    print(f&quot;Writer {id}: WAITING to write&quot;)<br>    with resource:<br>        print(f&quot;Writer {id}: WRITING&quot;)<br>        time.sleep(3)  # Simulate writing time<br>    print(f&quot;Writer {id}: FINISHED writing&quot;)<br><br># Create threads<br>threads = []<br>for i in range(3):<br>    threads.append(threading.Thread(target=reader, args=(i,)))<br>    threads.append(threading.Thread(target=writer, args=(i,)))<br><br># Start threads<br>for t in threads:<br>    t.start()<br><br># Wait for all threads to finish<br>for t in threads:<br>    t.join()</pre><p><strong>What Happens During the Simulation?</strong></p><ol><li><strong>Readers:</strong></li></ol><ul><li>Multiple readers can read concurrently like “Reader 0”, “Reader 1”, and “Reader 2” all read at the same time.</li><li>The first reader locks resources, preventing writers from interrupting.</li><li>The last reader unlocks resources, allowing writers to proceed.</li></ul><p>2. <strong>Writers:</strong></p><ul><li>Writers wait for resources to be released.</li><li>Once acquired, they write exclusively (no other readers/writers can access the resource).</li></ul><p>In this screenshot you can see that if there are readers using the resources the writers need to wait until the readers finish using it before the writers can access the resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*hOYAA-seGUNihmyS" /><figcaption>Screenshot of the simulation for readers and writers.</figcaption></figure><h3>Dining Philosophers Problem Simulation with Semaphores in C</h3><p>Provided by: Muhamad Iqbal bin Zulfikri</p><p>The Dining Philosophers problem is a classic synchronization challenge that illustrates potential deadlock scenarios in resource allocation. Imagine five philosophers seated around a circular table, where lies a single chopstick and creating a situation where each philosopher needs two chopsticks to eat, but must share these with their neighbors.</p><h3>Key components:</h3><ul><li><strong>Philosophers: </strong>Represent concurrent process/threads</li><li><strong>Chopsticks: </strong>Represent shared resources (typically semaphores)</li><li><strong>Table: </strong>The shared environment where synchronization must be enforced.</li></ul><h3>Problem Setup and Synchronization with Semaphores</h3><p>In our simulation, we implement the following synchronization mechanism:</p><ul><li><strong>Chopstick Semaphores</strong>: Binary semaphores (value 0 or 1) representing each chopstick.</li><li><strong>Table Mutex</strong>: A binary semaphore to prevent deadlock by ensuring only one philosopher can attempt to pick up chopsticks at a time</li></ul><h3>How Semaphores Work:</h3><ul><li><strong>Thinking Phase: </strong>Philosopher is not attempting to acquire resources</li><li><strong>Hungry Phase:</strong></li><li>Philosopher acquires table mutex</li><li>Attempts to pick up left then right chopstick</li><li>Releases mutex after acquiring both</li><li><strong>Eating Phase</strong>: Philosopher holds both chopsticks</li></ul><p><strong>Release Phase</strong>: Returns both chopsticks to the table</p><p><strong>Implementation in C</strong></p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;pthread.h&gt;<br>#include &lt;semaphore.h&gt;<br>#include &lt;unistd.h&gt;<br><br>#define NUM_PHILOSOPHERS 5<br>#define THINKING 0<br>#define HUNGRY 1<br>#define EATING 2<br><br>// Shared state<br>int state[NUM_PHILOSOPHERS];<br>sem_t chopsticks[NUM_PHILOSOPHERS];<br>sem_t table;<br><br>// Function to display current philosopher states<br>void display_states() {<br>    printf(&quot;\nCurrent States:\n&quot;);<br>    for (int i = 0; i &lt; NUM_PHILOSOPHERS; i++) {<br>        printf(&quot;Philosopher %d: &quot;, i);<br>        switch(state[i]) {<br>            case THINKING: printf(&quot;Thinking\n&quot;); break;<br>            case HUNGRY: printf(&quot;Hungry\n&quot;); break;<br>            case EATING: printf(&quot;Eating\n&quot;); break;<br>        }<br>    }<br>    printf(&quot;\n&quot;);<br>}<br><br>// Philosopher thread function<br>void* philosopher(void* num) {<br>    int id = *(int*)num;<br>    <br>    while(1) {<br>        // Thinking phase<br>        state[id] = THINKING;<br>        printf(&quot;Philosopher %d is thinking\n&quot;, id);<br>        sleep(rand() % 3 + 1);<br>        <br>        // Hungry phase<br>        state[id] = HUNGRY;<br>        printf(&quot;Philosopher %d is hungry\n&quot;, id);<br>        <br>        // Attempt to get chopsticks<br>        sem_wait(&amp;table);<br>        sem_wait(&amp;chopsticks[id]);<br>        sem_wait(&amp;chopsticks[(id + 1) % NUM_PHILOSOPHERS]);<br>        sem_post(&amp;table);<br>        <br>        // Eating phase<br>        state[id] = EATING;<br>        printf(&quot;Philosopher %d is eating\n&quot;, id);<br>        sleep(rand() % 2 + 1);<br>        <br>        // Release chopsticks<br>        sem_post(&amp;chopsticks[id]);<br>        sem_post(&amp;chopsticks[(id + 1) % NUM_PHILOSOPHERS]);<br>        <br>        display_states();<br>    }<br>}<br><br>int main() {<br>    pthread_t philosophers[NUM_PHILOSOPHERS];<br>    int ids[NUM_PHILOSOPHERS];<br>    <br>    // Initialize semaphores<br>    sem_init(&amp;table, 0, 1);<br>    for (int i = 0; i &lt; NUM_PHILOSOPHERS; i++) {<br>        sem_init(&amp;chopsticks[i], 0, 1);<br>        state[i] = THINKING;<br>    }<br>    <br>    // Create philosopher threads<br>    for (int i = 0; i &lt; NUM_PHILOSOPHERS; i++) {<br>        ids[i] = i;<br>        pthread_create(&amp;philosophers[i], NULL, philosopher, &amp;ids[i]);<br>    }<br>    <br>    // Wait for threads (infinite loop)<br>    for (int i = 0; i &lt; NUM_PHILOSOPHERS; i++) {<br>        pthread_join(philosophers[i], NULL);<br>    }<br>    <br>    // Clean up (unreachable in this example)<br>    for (int i = 0; i &lt; NUM_PHILOSOPHERS; i++) {<br>        sem_destroy(&amp;chopsticks[i]);<br>    }<br>    sem_destroy(&amp;table);<br>    <br>    return 0;<br>}</pre><h3>Key Features on the Implementation</h3><p><strong>Deadlock Prevention:</strong></p><ul><li>The table mutex ensures only one philosopher can attempt to pick up chopsticks at a time</li><li>Prevents the circular wait condition where all philosophers hold one chopstick</li></ul><p><strong>State Visualization:</strong></p><ul><li>The <strong>display_states</strong>() function shows each philosopher’s current activity</li><li>Clear console output tracks the system’s behavior in real-time</li></ul><p><strong>Random Timing:</strong></p><ul><li>Thinking and eating durations vary randomly to simulate realistic behavior</li><li>Helps demonstrate the solution’s robustness</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*aFeIqTgLyjwF4WRM" /></figure><p>Based on the screenshot of the Dining Philosophers program output can conclude the following:</p><p>In this screenshot where multiple philosophers can think and attempt to eat concurrently, but only a limited number of them are allowed to eat at the same time. Philosophers who are hungry must wait for the necessary chopsticks to become available. This coordination prevents deadlock and ensures that each philosopher eventually gets a chance to eat. The use of a semaphore controlling the number of philosophers attempting to eat at once (N-1 rule) successfully maintains a balanced and fair system.</p><h3>Why This Solution Works</h3><p><strong>Safety Properties:</strong></p><ul><li>Mutual exclusion: Each chopstick is used by at most one philosopher at a time</li><li>No deadlock: The table mutex prevents the circular wait condition</li><li>No starvation: Random timing ensures all philosophers eventually eat</li></ul><p><strong>Liveness Properties:</strong></p><ul><li>Progress: The system always moves forward</li><li>Bounded waiting: No philosopher waits indefinitely</li></ul><p><strong>Efficiency:</strong></p><ul><li>Allows maximum parallelism when possible</li><li>Minimal overhead from synchronization</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2115a8e996c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/process-synchronization-simulation-by-group-3-section-6-2115a8e996c0">Process Synchronization Simulation by Group 3 Section 6</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process Synchronization Simulation]]></title>
            <link>https://medium.com/operating-system-csci3300/process-synchronization-simulation-3360e06b654e?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/3360e06b654e</guid>
            <dc:creator><![CDATA[Faris]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:34:38 GMT</pubDate>
            <atom:updated>2025-05-26T11:34:38.521Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern operating systems, managing concurrent processes effectively is crucial to ensure the correct execution of tasks and prevent resource conflicts. This project focuses on simulating classic synchronization problems:</p><ol><li>Producer-Consumer</li><li>Readers-Writers</li><li>Dining Philosophers</li></ol><p>The purpose is to demonstrate how semaphores can be used to handle concurrency and maintain safe access to shared resources. This is done by Group 3 from Section 5.</p><p>First is <strong>Producer-Consumer Problem</strong></p><p>Producer-Consumer problem is a synchronization problem in operating systems and concurrent programming. It describes a system where <strong>Producers</strong> create data and add it to the buffer and <strong>Consumers</strong> take data from the buffer and process it. These two share buffers together and the buffer is fixed size ( bounded buffer), meaning it can only hold a limited number of items at one time. For this project, we will use a buffer size of 5 to perform the simulation in Python, with 2 producers and 2 consumers.</p><p>In this project we use the python threading module to create concurrent threads ( producers and consumers). To synchronize to the buffer we will use semaphores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*QirUv2LYe7j7QSfJ" /></figure><p>This is the code for Producer Thread Flow and Consumer Thread Flow:</p><p><strong>Producer Thread Flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*bf_mdEBoQCnOpsyl" /></figure><p>The producer waits for space in the buffer before entering it by calling empty_slot.acquire(). Following that, it will use mutex.acquire() to lock access to the buffer, preventing another thread from entering before completing the work in the buffer. After producing the item, the producer will add it to the buffer, unlock the buffer using mutex.release(), and use full_slots.release() to signal that the item has been added.</p><p><strong>Consumer Thread Flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*dxoCfVCV6P0AkHoK" /></figure><p>Before entering the buffer, the consumer calls full_slots.acquire() to check for available space. Following that, it will use mutex.acquire() to lock access to the buffer, preventing another thread from entering before the work in the buffer is complete. Following that, consumers consume the item, remove it from the buffer, unlock the buffer with mutex.release(), and use empty_slots.release() to indicate that the item has been inserted.</p><p><strong>Main Function to start the threads:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*wwoeL8qfdw-1khE8" /></figure><p>In the main function, we utilize two producers and two consumers to test whether the code has a problem or not. The code will run in 10 seconds.</p><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*yG9r3wozrWi2d-XG" /></figure><p>As shown in the output, Producer-0 enters the critical section first, produces data 42, stores it in the buffer, and then exits the critical section. Following that, consumers enter the critical section, consume 42, empty the buffer, and exit the critical section. The critical section was used properly meaning that no two threads can access the buffer simultaneously. This output confirms that the correct synchronization, proper use of semaphores, no deadlock and mutual exclusion.</p><p>The result for this problem is by using semaphores we can prevent a conflict between threads, unsafe access to the buffer and error like buffer overflow.</p><p>Now, we move on to <strong>Readers-Writers Problem</strong></p><p>The Readers-Writers problem is one of the classic synchronization problems that deals with a shared resource that can be read by multiple readers simultaneously but must be updated by a single writer. The goals are to let multiple readers be able to access the shared resource simultaneously, only one writer can access the shared resource at a time and no reader or writer should be starved. This simulation implements a reader-priority solution using the threading module in Python.</p><p>In the code below, read_count is used to keep track of active readers and resource_access is a semaphore to allow exclusive access for writers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*xvoCcXD2PxnVmbkC" /></figure><p>Code below is the reader thread function. In the entry section, it ensures that the first reader blocks any writers by locking the resource. In the critical section, it simulates reading from the shared data and the sleep mimics time taken to read. For the exit section, when reader finishes, read_count decrements and if it’s the last reader it’ll release the resource_acesss, allowing writers to enter. Lastly the rest period, it simulates time between read attempts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*nJjhrzWqJGuCtm56" /></figure><p>Code below is for the writer thread function. In the while loop, writers require exclusive access and they wait until no readers or writers are in the critical section. In the critical section, it updates the shared data and simulates writing time. Once finished, the writer releases the resource, allowing others to proceed. Then, it simulates time between write attempts. For the threads section, 3 reader threads and 2 writer threads are created. Threads are marked as daemon so they stop when the main program ends, all threads are started simultaneously. The main thread sleeps for 20 seconds to let the simulation run and then it prints a final message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/0*QRQaXet2msTbt3cY" /></figure><p>In the output, there are multiple readers reading together. This demonstrates that readers are not blocking each other. Writers wait until all readers are done and readers wait while a writer is active. For the alternating access, multiple readers can read at the same time and writers can only access the resource one at a time when no readers are active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*Po1F80vgdYpmECuU" /></figure><p>The last problem is <strong>Dining-Philosophers Problem</strong></p><p>The Dining-Philosopher Problem is another example of a synchronization problem happening in the operating systems. It illustrates the situations where multiple processes (philosophers) are competing for limited shared resources (chopsticks) in a way so that it can prevent the deadlock or starvation. Imagine there are 5 philosophers sitting around a circle table and between each philosopher has one chopstick (exactly 5 chopsticks in total). Each philosophers will follow this repeating process cycle which are:</p><ol><li>Thinking — Not hungry and not using chopsticks.</li><li>Hungry — Tries to pick up two adjacent chopsticks to eat. (Wait)</li><li>Eating — Need both chopsticks to eat, and release them after eating. (Signal)</li></ol><p>In order for philosophers to eat, they must acquire both left and right chopsticks. This situation indicates that each philosopher is dependent on their neighbors.</p><p>In this part, we will implement the Dining-Philosophers Problem using the threading mode in python.</p><p>The code below initializes the number of philosophers to 5 people and each of the chopsticks is represented as a binary semaphore (1 = available, 0 = not available). While ‘waiter’ which is a counting semaphore is used to ensure that deadlock cannot occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*Die-XNVqzNPI8maO" /></figure><p><strong>In Dining-Hall Thread Flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*UdToB3UXbp4blD_I" /></figure><p>In this part of the code, each philosopher runs in an infinite loop which alternates between <strong>thinking </strong>and <strong>eating</strong>. The cycle begins with each philosopher thinking in a period of time. When the philosopher becomes hungry, it attempts to acquire the waiter’s semaphore ( waiter.acquire() ) in order to access chopsticks. Once the permission is granted, the philosopher acquires the chopstick on their left and right (if available) and proceeds to eat (<strong>critical section</strong>) in a period of time. If there is a philosopher is in a hungry state and then its neighbor is still in an eating state, the philosopher needs to wait for the neighbor to exit the critical state and put down the chopsticks first in order to acquire a chopstick to enter the critical state. This cycle repeats continuously, stimulating the philosophers’ ongoing struggle to eat while avoiding deadlock.</p><p><strong>Main Function for threading:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*lQyVoHONcf_14_0a" /></figure><p>This code is generally responsible for setting up and running the simulation. It starts with creating a list of threads that each thread represents a philosopher that will execute the <strong>philosopher function</strong> to stimulate the philosopher’s action of thinking, hunger, and eating. All threads are designed as daemon threads after they are created to ensure that they will terminate automatically when the main thread ends. All philosophers then started the cycle, allowing them to run their think-eat loop concurrently.</p><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*oSBkbt15e6eoiYuJ" /></figure><p>From the output, it shows that all philosophers start with a thinking state with a random period of time (1–3 seconds). After a while, Philosopher-1 becomes hungry and attempts to acquire its adjacent chopsticks to eat. Since there is no philosopher using the chopstick, Philosopher-1 successfully acquires both chopsticks and enters the critical section (eating). Then, Philosopher-2 changes state to hunger. Since Philosopher-1 is still in a critical state which means that it is still using chopsticks, Philosopher-2 needs to wait for Philosopher-1 to exit the critical state and put down the chopsticks and return to the thinking state in order to start eating. This cycle repeats for the other philosophers as well. With this output, it demonstrates a solution for synchronization problem using semaphore which can prevent a deadlock or starvation for processes to be assigned to its thread smoothly.</p><p><strong>Conclusion:</strong></p><p>This project helped us understand and apply core concepts of process synchronization using semaphores. By simulating the Producer-Consumer, Readers-Writers, and Dining Philosophers problems, we demonstrated how to manage concurrent processes safely and effectively. Each solution ensured mutual exclusion, avoided deadlocks, and showed clear process state transitions, reinforcing the practical importance of synchronization in operating systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3360e06b654e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/process-synchronization-simulation-3360e06b654e">Process Synchronization Simulation</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering the Hidden Workings of Linux: A Hands-On Dive into Processes and Threads]]></title>
            <link>https://medium.com/operating-system-csci3300/uncovering-the-hidden-workings-of-linux-a-hands-on-dive-into-processes-and-threads-edccf6645f4c?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/edccf6645f4c</guid>
            <dc:creator><![CDATA[Sundus]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:34:15 GMT</pubDate>
            <atom:updated>2025-05-26T11:34:15.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>In the world of operating systems, concepts like <em>processes</em> and <em>threads</em> are often explained through theory, but understanding them practically can be a game-changer. During a recent hands-on exploration of the <strong>Linux operating system</strong>, I had the chance to go beyond textbooks and interact directly with how Linux handles multitasking behind the scenes.</h3><p>Using simple but powerful terminal tools and a basic multithreaded C program, I explored how <strong>processes</strong> (full running programs) and <strong>threads</strong> (lightweight execution units) function and coexist within the system. What I found was both enlightening and empowering.</p><h3>Setting the Stage: Tools and Environment</h3><p>To begin, I set up a <strong>Ubuntu-based Linux virtual machine</strong>. My main toolkit included:</p><ul><li>ps aux, top, htop, ps -ef – for monitoring processes</li><li>top -H -p &lt;PID&gt; – for tracking threads within a process</li><li>/proc/&lt;pid&gt;/task – for accessing thread-level data</li><li>strace – for tracing system calls</li><li>A simple <strong>C program using pthreads</strong> to simulate multithreading</li></ul><p>These tools were windows into the system’s inner workings, allowing me to watch Linux manage and schedule multiple tasks in real time.</p><h3>Exploring Processes and Threads</h3><h3>1. Observing Active Processes</h3><p>Using commands like ps aux and topI was able to view a live snapshot of all currently running processes. Each line represented a unique process with its Process ID (PID), memory and CPU usage, and user ownership. This helped me understand how the OS juggles hundreds of tasks at once—some user-initiated, others essential to system stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SivEc9lQXByG0RbX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ax8W1bIt7a9dCDIx.png" /></figure><h3>2. Diving into Thread Management</h3><p>With htop In tree view and top -H -pI monitored individual threads within a process. Navigating through /proc/&lt;pid&gt;/taskI discovered that threads, while separate execution flows, share memory and resources with their parent process, making them ideal for efficient multitasking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpUCEhw_Zujg_Dnl.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oL1XtldYENPsp5pe.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KSDSp8uXfykme3GG.png" /></figure><h3>3. Building My Multithreaded Program</h3><p>To deepen my understanding, I wrote a simple <strong>C program</strong> that uses pthread_create() to spawn a thread that print numbers from 0 to 9. The main thread waits for it to complete using pthread_join(). I then monitored the thread’s lifecycle using system tools—watching it appear and vanish in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HYpnB8UnRQQrZyFm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0zbN5JcpIRCoIj71.png" /></figure><h3>4. Bonus Insight: Tracing System Calls with strace</h3><p>Curious about what happens behind the scenes, I used strace to trace the system calls of a running program. This opened a new dimension of understanding, revealing the constant, low-level communication between software and the Linux kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*xM1r8U791l81DfFT.png" /></figure><h3>Key Takeaways</h3><p>This exploration turned abstract operating system concepts into something tangible and intuitive. Observing real-time process and thread behavior gave me a deeper appreciation for how Linux manages multitasking at its core. I learned that threads are efficient, lightweight units ideal for handling concurrent tasks, and that Linux provides powerful tools to inspect and manage these components with precision. Writing and monitoring a simple multithreaded program made the inner workings of the system feel more accessible and less intimidating. Overall, this hands-on experience not only strengthened my technical understanding but also sparked a deeper interest in system-level programming and the incredible complexity that happens behind every command we run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edccf6645f4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/uncovering-the-hidden-workings-of-linux-a-hands-on-dive-into-processes-and-threads-edccf6645f4c">Uncovering the Hidden Workings of Linux: A Hands-On Dive into Processes and Threads</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Process Synchronization Through Python Simulations]]></title>
            <link>https://medium.com/operating-system-csci3300/understanding-process-synchronization-through-python-simulations-1d79f3a31243?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/1d79f3a31243</guid>
            <dc:creator><![CDATA[Sundus]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:32:22 GMT</pubDate>
            <atom:updated>2025-05-28T08:11:32.974Z</atom:updated>
            <content:encoded><![CDATA[<p>By Sundus</p><p>Group Members and Roles:</p><ol><li>SUNDUS 2312638 — Project Coordinator &amp; Presenter</li><li>MUKRED MARWA MUSTAFA ALI 2110126 — Producer-Consumer Lead</li><li>ABDIWAHAB BALQIS MOHAMED 2227796 — Readers-Writers Lead</li><li>SALMAN MOHAMED MOHAMUD 2220269 — Dining Philosophers Lead</li></ol><p>As part of our<strong> Operating Systems </strong>coursework, we embarked on a project to simulate and understand how concurrent processes can access shared resources without conflicts. To bring these concepts to life, we implemented Python-based simulations of three classical synchronization problems: <strong>Producer-Consumer</strong>, <strong>Readers-Writers</strong>, and <strong>Dining Philosophers</strong>.</p><p>These problems are foundational in computer science because they represent real-world challenges in concurrent programming. We aimed to explore how <strong>semaphores</strong> and <strong>mutex locks</strong> help ensure safe process synchronization, prevent race conditions, and avoid deadlocks.</p><h3>Producer-Consumer Problem</h3><p>The <strong>Producer-Consumer problem</strong> models a scenario where a producer thread generates data and stores it in a bounded buffer, while a consumer thread retrieves and uses it. The key challenge is to ensure the producer does not add items when the buffer is full and the consumer does not remove items when the buffer is empty.</p><p>In our simulation, we used:</p><ul><li>A <strong>counting semaphore</strong> to track empty and full slots.</li><li>A <strong>mutex lock</strong> to protect the shared buffer from concurrent modifications.</li></ul><p>This setup allowed us to simulate synchronized production and consumption in a safe, controlled manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0b47n86bxKvfPGZZtRoCaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*B9kXo72N8va5pNT2KXHZBA.jpeg" /></figure><h3>Readers-Writers Problem</h3><p>The <strong>Readers-Writers problem</strong> illustrates the balance between data accessibility and integrity. Multiple readers can read from shared data simultaneously, but when a writer needs access, it must do so exclusively to prevent inconsistency or corruption.</p><p>Our solution involved:</p><ul><li>A shared <strong>reader count</strong> variable to track active readers.</li><li>A <strong>mutex</strong> to protect access to the reader count.</li><li>A <strong>writer lock (semaphore)</strong> to ensure exclusive writing access.</li></ul><p>This implementation allowed multiple readers to work concurrently while ensuring that writers could write without interference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYRiZdlE7iVjRcK5QYdVYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qez5rfk7pMbA2nw6ZShFdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*wh6BpDPRTVGdlEAqg5gP-w.jpeg" /></figure><h3>Dining Philosophers Problem</h3><p>The <strong>Dining Philosophers problem</strong> is a classic synchronization challenge illustrating potential deadlocks when multiple processes require multiple shared resources simultaneously. In this scenario, five philosophers alternately think and eat, but each needs two forks (shared resources) to eat.</p><p>We represented each fork as a <strong>binary semaphore</strong>. To prevent deadlocks, we implemented an ordering strategy that ensures philosophers always pick up forks in a specific sequence, minimizing the chance of circular wait.</p><p>This simulation highlighted the importance of resource hierarchy and structured access in preventing deadlock conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBxbekvcKvjQtA8JxYuQxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*h6olJI9c1LwmvOdbshB6xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*HJgX88PxQwgcn1qJV9PwLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*nmGS-BxJQdPRWCGD_zld7g.png" /></figure><h3>Final Reflection</h3><p>After testing all three simulations, we confirmed that each process followed synchronization rules correctly, with no deadlocks or starvation. Using Python’s threads and semaphores allowed us to bring abstract operating system concepts to life.</p><p>Although working with semaphores was challenging at first, seeing the simulations function smoothly deepened our understanding and built our confidence. This project helped connect classroom theory to real-world applications, preparing us for future work in concurrent systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d79f3a31243" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/understanding-process-synchronization-through-python-simulations-1d79f3a31243">Understanding Process Synchronization Through Python Simulations</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process Synchronization: A Simple Python Simulation]]></title>
            <link>https://medium.com/operating-system-csci3300/process-synchronization-a-simple-python-simulation-0cf003c3f489?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/0cf003c3f489</guid>
            <dc:creator><![CDATA[Abdulghafar Abdulahi]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:31:35 GMT</pubDate>
            <atom:updated>2025-05-26T11:31:35.317Z</atom:updated>
            <content:encoded><![CDATA[<p>By Abdulghafar Abdulahi Ibrahim</p><p>Group Members and Roles:</p><p>ABDULGAFAR ABDULAHI 2311279— Project Coordinator &amp; Presenter</p><p>ASMA ESMAIL 2212282— Producer-Consumer Lead</p><p>NEWAL YESHAK 2315376 — Readers-Writers Lead</p><p>ADIL EMADELDIN 2320799 — Dining Philosophers Lead</p><h3><strong>Introduction :</strong></h3><p>In the OS course, our project involved synchronizing multiple processes. We decided to mimic the Producer-Consumer, Readers-Writers, and Dining philosopher problems, which show how several processes must coordinate to use shared resources without affecting each other.</p><p>We developed the project using Python and the threading library. We relied on semaphores to achieve synchronization. By using semaphores, the programmer ensures that only a permitted number of processes get access to a shared resource. By displaying what was happening each time on the console, we could see how the different processes were being completed.</p><h3><strong>What Are Semaphores? :</strong></h3><p>Semaphores are designed to maintain control access to shared resources used by different threads at the same time. Basically, they confine how many processes or threads can interfere with the same section of code at once. Take counting semaphores as an example. These let a limited number of threads use a resource, whereas binary semaphores (also referred to as mutexes) allow only one thread access at a time. With semaphores, we ensure data is not damaged and processes are not affected by each other’s access to data.</p><h3><strong>Simulation 1: Producer-Consumer Problem :</strong></h3><p>We set up a common buffer in the Producer-Consumer simulation. A producer will place items in the buffer, and a consumer will remove them. By using semaphores, we prevented the producer from adding when the buffer was full, and the consumer from removing when it was already empty. The mutex prevented multiple threads from accessing the buffer at one time. Everything functioned nicely and demonstrated the purpose of semaphores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*1aSSG4E7jW2raU3xcipVfA.png" /><figcaption>producer_output</figcaption></figure><pre>import threading<br>import time<br>import random<br><br># Shared buffer and max size<br>buffer = []<br>MAX_SIZE = 5<br><br># Semaphores<br>empty = threading.Semaphore(MAX_SIZE)<br>full = threading.Semaphore(0)<br>mutex = threading.Semaphore(1)<br><br># Producer function<br>def producer():<br>    count = 0<br>    while count &lt; 10:<br>        time.sleep(random.uniform(0.5, 1.5))<br>        empty.acquire()<br>        mutex.acquire()<br><br>        item = f&quot;Item-{count}&quot;<br>        buffer.append(item)<br>        print(f&quot;[Producer] Produced: {item}&quot;)<br><br>        mutex.release()<br>        full.release()<br>        count += 1<br><br># Consumer function<br>def consumer():<br>    count = 0<br>    while count &lt; 10:<br>        full.acquire()<br>        mutex.acquire()<br><br>        item = buffer.pop(0)<br>        print(f&quot;[Consumer] Consumed: {item}&quot;)<br><br>        mutex.release()<br>        empty.release()<br>        time.sleep(random.uniform(0.5, 1.5))<br>        count += 1<br><br># Create and start threads<br>t1 = threading.Thread(target=producer)<br>t2 = threading.Thread(target=consumer)<br><br>t1.start()<br>t2.start()<br><br>t1.join()<br>t2.join()<br><br>print(&quot;\n[✓] Simulation complete!&quot;)</pre><h3><strong>Simulation 2: Readers-Writers Problem :</strong></h3><p>The following step was to focus on the Readers-Writers problem. The focus here was on controlling permissions. There was a rule that all readers had to leave before a writer entered and vice versa. We kept track of the number of readers with a counter and made sure writers could have sole access when required. We now know a process for handling concurrency without compromising data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*m48D_P2rzEuPhYEIQnR6-g.png" /><figcaption>readers_output</figcaption></figure><pre>import threading<br>import time<br>import random<br><br># Shared data<br>rc = 0  # reader count<br>rc_lock = threading.Semaphore(1)  # protects rc<br>res_lock = threading.Semaphore(1)  # locks resource<br><br># Reader<br>def reader(rid):<br>    global rc<br>    time.sleep(random.uniform(0.1, 0.5))  # reader arrives<br><br>    rc_lock.acquire()<br>    rc += 1<br>    if rc == 1:<br>        res_lock.acquire()<br>    rc_lock.release()<br><br>    # Reading<br>    print(f&quot;[Reader-{rid}] started reading&quot;)<br>    time.sleep(random.uniform(0.5, 1.0))<br>    print(f&quot;[Reader-{rid}] finished reading&quot;)<br><br>    rc_lock.acquire()<br>    rc -= 1<br>    if rc == 0:<br>        res_lock.release()<br>    rc_lock.release()<br><br># Writer<br>def writer(wid):<br>    time.sleep(random.uniform(0.1, 0.5))  # writer arrives<br><br>    res_lock.acquire()<br>    print(f&quot;[Writer-{wid}] started writing&quot;)<br>    time.sleep(random.uniform(0.5, 1.0))<br>    print(f&quot;[Writer-{wid}] finished writing&quot;)<br>    res_lock.release()<br><br># Threads list<br>threads = []<br><br># Make 3 readers<br>for i in range(3):<br>    t = threading.Thread(target=reader, args=(i,))<br>    threads.append(t)<br><br># Make 2 writers<br>for i in range(2):<br>    t = threading.Thread(target=writer, args=(i,))<br>    threads.append(t)<br><br># Start all<br>for t in threads:<br>    t.start()<br><br># Wait for all to finish<br>for t in threads:<br>    t.join()<br><br>print(&quot;\n[✓] Readers-Writers Simulation Complete!&quot;)</pre><h3><strong>Simulation 3: Dining Philosophers Problem :</strong></h3><p>The last simulation displayed was the Dining Philosophers Problem. Five philosophers assemble at a table, with each of them needing two forks to eat. We used forks to represent semaphores and put in place a strategy that avoided the problem of philosophers waiting for forks forever. They could eat only if both forks were ready, and switch back to thinking after finishing. This experience showed how complicated synchronizing multiple resources can be at times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*6tPC99ArinIrN4FKK4c2wQ.png" /><figcaption>philosophers_output</figcaption></figure><pre>import threading<br>import time<br>import random<br><br># Number of philosophers and forks<br>N = 5<br>forks = [threading.Semaphore(1) for _ in range(N)]<br><br># Philosopher function<br>def dine(pid):<br>    for _ in range(2):  # Eat two times<br>        print(f&quot;[Philosopher-{pid}] is thinking&quot;)<br>        time.sleep(random.uniform(0.5, 1.5))<br><br>        left = pid<br>        right = (pid + 1) % N<br><br>        # Philosopher 4 picks right fork first to avoid deadlock<br>        if pid == N - 1:<br>            forks[right].acquire()<br>            forks[left].acquire()<br>        else:<br>            forks[left].acquire()<br>            forks[right].acquire()<br><br>        print(f&quot;[Philosopher-{pid}] picked up forks and is eating&quot;)<br>        time.sleep(random.uniform(0.5, 1.5))<br>        print(f&quot;[Philosopher-{pid}] put down forks and is thinking again&quot;)<br><br>        forks[left].release()<br>        forks[right].release()<br><br># Create threads<br>threads = []<br>for i in range(N):<br>    t = threading.Thread(target=dine, args=(i,))<br>    threads.append(t)<br>    t.start()<br><br># Wait for all threads<br>for t in threads:<br>    t.join()<br><br>print(&quot;\n[✓] Dining Philosophers Simulation Complete!&quot;)</pre><h3>Results and Reflection :</h3><p>After solving all three problems, we printed out the console output and attached it to our report. The processes were found to operate according to the synchronization rules, and there were neither deadlocks nor starvation. We found out that Python allows us to simulate issues with operating systems by making use of threads and semaphores.</p><p>It was nice to see how everything studied in class came to life in code. Using semaphores correctly was tough at the beginning, but when I tested the programs in action, everything became clearer. It strengthened our confidence in using concurrent systems in future classes and jobs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cf003c3f489" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/process-synchronization-a-simple-python-simulation-0cf003c3f489">Process Synchronization: A Simple Python Simulation</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Processes and Threads in Linux]]></title>
            <link>https://medium.com/operating-system-csci3300/understanding-processes-and-threads-in-linux-2390f0a1fe8f?source=rss----2a57dafbe033---4</link>
            <guid isPermaLink="false">https://medium.com/p/2390f0a1fe8f</guid>
            <dc:creator><![CDATA[salman mohamed ]]></dc:creator>
            <pubDate>Tue, 20 May 2025 00:40:37 GMT</pubDate>
            <atom:updated>2025-05-20T00:40:37.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>In this Operating Systems task, I explored how processes and threads behave in a Linux environment. By writing a multithreaded C program and using system monitoring tools like ps, top, and strace, I observed how the OS handles multiple tasks at the same time. This activity allowed me to connect what I learned in theory with how real systems manage process execution, resource usage, and system calls.</p><h3>Setup:</h3><p>The activity was carried out on a Kali Linux virtual machine installed using VirtualBox. I verified that essential tools such as ps, top, and /proc were already available by default. Additional utilities like htop and pstree were installed manually using the package manager. I also ensured the GCC compiler was installed so I could write and run a simple multithreaded C program using pthread_create() and pthread_join(). Screenshots were taken throughout the steps to document the observations.</p><h3>What Was My Experiment?:</h3><p>The first step involved using the ps aux command to view all active processes along with details such as their PID, CPU, and memory usage. It was clear that even when the system appeared idle, many background processes were still running.</p><p>Next, I used top to observe system activity in real-time, which allowed me to track how resources were being used by different processes. To understand process relationships, I ran ps -eo pid,ppid,cmd and noted that most user programs were child processes of shell sessions or background system services. This gave insight into how the process hierarchy is structured in Linux.</p><h3>Viewing All Running Processes with ps aux:</h3><p>The output of ps aux provides a detailed list of all active processes on the system, including system services and user-level programs. Each row includes information such as the process ID (PID), CPU and memory usage, and the command that launched the process. Most of the processes shown are system-level tasks, such as kernel workers and background daemons, which are essential for maintaining system operations even when no applications are open. This command is useful for getting a complete snapshot of all running activity in the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*oqTBCA6GNwEykna-S27Njg.png" /></figure><h3>Monitoring System Performance with top and Counting Processes :</h3><p>The top command shows a live, real-time summary of system activity. It displays CPU usage, memory statistics, and a dynamic list of the most active processes. In this output, we see that most CPU time is idle (99.8%), indicating the system is under light load. The total number of tasks and threads is also shown. Below that, the ps aux | wc command counts the number of processes listed—236 in total—confirming the system runs many background tasks and services continuously, even with minimal user interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFvb5Hg8L4yxjxdCDJCMew.png" /></figure><h3>Counting the Number of Active Processes with ps aux | wc</h3><p>The command ps aux | wc is used to count the number of lines, words, and characters in the output of ps aux. In this case, it returned <strong>236 lines</strong>, meaning there are 236 active processes currently running on the system. This quick method helps verify the total process count without manually scrolling through all entries. It’s useful for getting a high-level view of system load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*PuOaPPV4EG5GZ9QMNqjUAA.png" /></figure><h3>Parent-Child Structure Explanation:</h3><p>The output of pstree -p shows the hierarchical structure of running processes on the system. At the top is the <strong>systemd(1)</strong> process, which is the <strong>init process</strong> and the root of all others. From there, various system services and user applications branch out as child processes.</p><p>For example:</p><ul><li>NetworkManager(682) is a child of systemd(1) and has several subprocesses such as ModemManager.</li><li>VBoxClient and VBoxService processes are spawned under systemd to support VirtualBox guest additions.</li><li>Graphical sessions like gdm-x-session, gnome-session, and Xorg are grouped together, indicating how the graphical desktop environment is structured.</li><li>accounts-daemon, cron, and dbus-daemon are also shown as direct children of systemd, reflecting standard background services.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-oVtECvO3czDFUnnwUeRbA.png" /></figure><p>This tree structure helps visualize how processes are related, with parent processes spawning children that perform specific system or user tasks.</p><h3>Finding a Target PID (Process ID):</h3><p>The ps aux command lists all currently running processes along with their details. Each row represents a process and includes information such as the <strong>user</strong>, <strong>PID</strong> (process ID), <strong>CPU and memory usage</strong>, and the <strong>command</strong> that launched the process.</p><p>In the screenshot, we can see that many system processes are running under the user root, including:</p><ul><li>The <strong>init process (</strong><strong>/sbin/init splash)</strong> with PID 1, which is the first process started by the kernel.</li><li>Multiple <strong>kernel threads</strong> such as [kthread], [migration/X], [rcu_tasks_kthread], and [cpuhp/X], which handle various low-level system operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*Pik1WBzFoDiI2kCYWEt2yg.png" /></figure><p>These processes have <strong>very low or zero CPU and memory usage</strong>, indicating they are mostly idle or waiting for specific system events.</p><p>To proceed with thread monitoring, any of these PIDs can be selected — for example, you could pick one like PID 2 ([kthread]) or any user-level application that shows up when more interactive software is running.</p><h3>View Threads with top:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*VSJh2ENXC1M6usZjhWTzyg.png" /></figure><p>The command top -H -p 1 is used to display all threads belonging to a specific process—in this case, process ID 1. The -H flag tells top to break down the process into its individual threads. This is useful when analyzing multithreaded applications to see how each thread behaves in terms of CPU usage and system activity. The screenshot also shows the help output, listing various options available in top.</p><h3>Explore Threads in /proc:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*avtXIwExmHujlb5mHqgsAA.png" /></figure><p>In this step, I navigated to the /proc/1/task/ directory, which contains subdirectories representing each thread under process ID 1. Each thread has its own folder named after its thread ID (TID). This method gives a low-level view of how Linux internally organizes threads under each process, and helps visualize thread management at the kernel level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*R7mmfjQw8yVbxgu9Rt9ZXQ.png" /></figure><h3>Title: Compiling and Running a Multithreaded C Program:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*933prCwGiQnrRffGNxNsbw.png" /></figure><p>In this task, I first compiled a multithreaded C program using the command gcc -pthread thread_example.c -o thread_example, which links the pthread library necessary for thread creation. Running the program with ./thread_example successfully launched three threads—Thread 0, Thread 1, and Thread 2—all of which executed and completed their tasks. To observe system behavior during execution, I used the top command to monitor real-time performance. The output showed that no threads were actively running at that specific moment and that the CPU was mostly idle at 99.5%, with around 1114.6 MiB of memory in use. This helped me understand both how threads function in a process and how to monitor resource usage during program execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wrSK1pzbGpwI81L7ddHXQ.png" /></figure><h3>Conclusion:</h3><p>This activity helped me understand how processes and threads work inside a Linux operating system. Writing and running a simple threaded C program using pthread_create() allowed me to see how threads operate within a process and how they can run concurrently. I also learned how to compile programs with gcc and observe their behavior using tools like ps, top, and strace. These tools showed me how many processes are always running in the background, how system resources are used, and how threads are managed. Overall, this hands-on experience made the theoretical concepts from class much clearer and showed me how the operating system manages multitasking in real-time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2390f0a1fe8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operating-system-csci3300/understanding-processes-and-threads-in-linux-2390f0a1fe8f">Understanding Processes and Threads in Linux</a> was originally published in <a href="https://medium.com/operating-system-csci3300">Operating System CSCI 3300</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>