ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-505Synchronization
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-505

    Operating Systems

    Progress0 / 20 done
    Topics20
    1History and Goals2Evolution of Multi-User Systems3Process and CPU Management4Multithreading5Kernel and User Modes6Protection7Problems of Cooperative Processes8Synchronization9Deadlocks10Memory Management and Virtual Memory11Relocation12External Fragmentation13Paging and Demand Paging14Secondary Storage15Security and Protection16File Systems17I/O Systems18Introduction to Distributed Operating Systems19Scheduling and Dispatch20Introduction to Concurrency
    9 min read
    Topic 8 of 20
    Topic Study Note Illustration
    08

    Synchronization

    Synchronization in operating systems refers to the coordination of processes or threads in a way that ensures that shared resources are accessed in a controlled manner. When...

    Synchronization in Operating Systems

    Synchronization in operating systems refers to the coordination of processes or threads in a way that ensures that shared resources are accessed in a controlled manner. When multiple processes or threads need to access the same resources or perform tasks that depend on each other, synchronization mechanisms are required to ensure correctness and prevent issues like race conditions, deadlocks, or data corruption.

    Synchronization is critical in multi-threading and multi-processing environments where concurrent execution of processes or threads can cause unpredictable results if not properly coordinated.

    1. Why Synchronization is Needed

    In a system where multiple processes or threads are executing simultaneously, resources like memory, I/O devices, and files may be shared. Without synchronization, two or more processes or threads may simultaneously try to access or modify shared data, leading to:

    • Race conditions: Where the result of operations depends on the timing or sequence of execution of the processes.
    • Data corruption: If two processes simultaneously write to the same data structure, the data may be corrupted.
    • Inconsistent system states: If processes are not coordinated, they may leave shared data or resources in inconsistent states.

    Thus, synchronization is necessary to maintain data integrity and ensure the system works as expected.

    2. Types of Synchronization

    There are two main types of synchronization in operating systems:

    a) Process Synchronization:

    This type of synchronization ensures that multiple processes coordinate their actions to access shared resources safely, without causing conflicts or corruption.

    b) Thread Synchronization:

    Thread synchronization ensures that threads within a process that share data or resources do not interfere with each other.

    3. Common Synchronization Problems

    Synchronization issues occur when processes or threads share resources or perform dependent tasks:

    a) Race Condition:

    A race condition happens when the outcome of a process depends on the sequence or timing of uncontrollable events (like the order of execution of instructions). This can lead to inconsistent results.

    Example: Two processes, A and B, are trying to update the same bank account balance. Without synchronization, both may read the balance simultaneously, make changes, and write back the new balance, resulting in lost updates.

    b) Deadlock:

    Deadlock (computer science)
    Visual ReferenceDeadlock (Computer Science)
    Wikipedia

    Deadlock occurs when two or more processes are blocked indefinitely, each waiting for the other to release resources. This creates a circular wait, preventing any process from making progress.

    Example: Process A holds Resource 1 and waits for Resource 2, while Process B holds Resource 2 and waits for Resource 1, causing both to be stuck.

    c) Starvation:

    Starvation happens when a process is perpetually denied access to resources because other processes are always prioritized. This can lead to indefinite waiting for the affected process.

    Example: In a priority-based scheduling system, a low-priority process may never get CPU time because higher-priority processes keep executing.

    4. Synchronization Mechanisms

    Operating systems provide various mechanisms to ensure proper synchronization between processes and threads:

    a) Locks (Mutexes)

    A lock (or mutex, short for mutual exclusion) is a synchronization primitive used to enforce mutual exclusion, allowing only one process or thread to access a critical section (a part of the code that accesses shared resources) at a time.

    • When a process or thread acquires a lock, it prevents other processes or threads from entering the critical section until it releases the lock.
    • Deadlock Prevention: If used improperly (e.g., when locks are not acquired in a consistent order), locks can lead to deadlocks.

    Example:

    mutex.lock()     # Acquire lock
    # Critical section
    
    
    
    <figure class="sq-async-media sq-async-single my-6 sm:my-8 rounded-xl border border-slate-200/80 bg-white shadow-xs dark:border-[#262626] dark:bg-[#141414] overflow-hidden not-prose hidden" style="display: none;" data-sq-async-media="single"><div class="sq-media-frame relative w-full overflow-hidden aspect-[16/9] bg-slate-100 dark:bg-[#1c1c1c]" style="aspect-ratio: 16 / 9;" data-sq-async-image="true" data-query="Semaphore (programming)"><img class="sq-media-img absolute inset-0 w-full h-full object-cover opacity-0 transition-opacity duration-300 cursor-zoom-in" alt="Semaphore (programming)" loading="lazy" /></div><figcaption class="px-3.5 py-2.5 sm:px-4 sm:py-3 flex items-center justify-between text-xs text-slate-600 dark:text-neutral-300 border-t border-slate-100 dark:border-[#222] bg-white dark:bg-[#141414]"><div class="flex items-center gap-2 min-w-0"><span class="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2 py-0.5 text-[10.5px] font-semibold text-indigo-700 dark:bg-indigo-950/50 dark:text-indigo-300 shrink-0"><svg class="size-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="m21 21-4.3-4.3"/><circle cx="11" cy="11" r="8"/></svg>Visual Reference</span><span class="sq-media-title font-medium truncate text-slate-700 dark:text-neutral-200" title="Semaphore (programming)">Semaphore (Programming)</span></div><a href="https://en.wikipedia.org/w/index.php?search=Semaphore%20(Programming)" target="_blank" rel="noopener noreferrer" class="sq-media-wiki-link shrink-0 ml-2 inline-flex items-center gap-1 text-[11px] font-medium text-indigo-600 hover:text-indigo-700 dark:text-indigo-400 hover:underline"><span>Wikipedia</span><svg class="size-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></a></figcaption></figure>
    
    
    
    mutex.unlock()   # Release lock
    

    b) Semaphores

    A semaphore is a signaling mechanism used to control access to shared resources. It maintains a counter that represents the number of available resources. There are two types of semaphores:

    • Counting Semaphore: Can have any integer value and is used to manage a pool of resources.

    • Binary Semaphore (or Mutex): Can only take values 0 or 1, essentially functioning as a lock.

    • Down (P) Operation: Decreases the semaphore value and blocks the process if the value is zero.

    • Up (V) Operation: Increases the semaphore value, possibly releasing a blocked process.

    Example:

    semaphore.down()  # Wait (decreases value)
    # Critical section
    semaphore.up()    # Signal (increases value)
    

    c) Monitors

    A monitor is a higher-level synchronization construct that combines mutual exclusion with the ability to wait for a condition to be met. Monitors are used to protect shared resources and ensure that only one process can access the resource at a time.

    • A monitor consists of a mutex lock and condition variables.
    • Condition variables allow processes to wait until a particular condition is true (e.g., when a resource becomes available).

    Example:

    monitor.lock()        # Enter monitor
    # Critical section
    monitor.wait()        # Wait for condition
    monitor.signal()      # Signal condition change
    monitor.unlock()      # Exit monitor
    

    d) Condition Variables

    A condition variable is a synchronization primitive that enables threads or processes to wait for certain conditions to be true. Condition variables are often used in conjunction with a lock (mutex) to manage access to shared resources.

    • Wait: A thread can wait on a condition variable until another thread signals that the condition has been met.
    • Signal: A thread signals a condition variable to wake up one or more waiting threads.

    Example (using Python-style pseudocode):

    mutex.lock()
    while condition is not met:
        condition_variable.wait()  # Wait for condition to be true
    # Proceed with critical section
    mutex.unlock()
    

    e) Read-Write Locks

    Read-write locks allow multiple threads to read shared data concurrently but ensure exclusive access to a writer when modifying the data. This type of lock is useful when read operations are frequent and write operations are less frequent.

    • Read Lock: Multiple readers can acquire the lock simultaneously.
    • Write Lock: Only one writer can acquire the lock, and no readers are allowed to access the resource during a write operation.

    Example:

    read_lock.acquire()    # Multiple threads can read
    write_lock.acquire()   # Only one thread can write
    

    5. Deadlock and Starvation Prevention in Synchronization

    a) Deadlock Prevention

    To prevent deadlocks, the system must ensure that at least one of the Coffman conditions (mutual exclusion, hold and wait, no preemption, circular wait) is violated.

    • Avoid Circular Wait: Assign a total ordering to resources and require that processes request resources in a specific order to avoid circular waits.
    • Preemption: If a process holding some resources is waiting for other resources, the OS can preempt resources from it and assign them to another process.

    b) Starvation Prevention

    To prevent starvation, the system can use techniques like aging, where processes waiting for resources gradually gain higher priority to ensure they eventually get access.

    6. Synchronization in Multi-Threading

    In a multi-threaded environment, synchronization ensures that threads can safely share data, especially when they run concurrently on multiple processors or cores.

    • Atomic Operations: Atomic operations are indivisible actions that are completed in one step without interruption. These are useful for low-level synchronization (e.g., incrementing a counter).

    • Thread-Specific Data: To avoid the need for synchronization, some applications use thread-specific data, where each thread works with its own local data.

    7. Challenges in Synchronization

    While synchronization ensures correctness, it introduces several challenges:

    • Performance Overhead: Synchronization mechanisms, especially locks, can introduce significant overhead, particularly in high-concurrency environments.
    • Complexity: Designing systems that synchronize efficiently without introducing bugs like deadlocks or race conditions can be complex.
    • Scalability: In systems with a large number of processes or threads, synchronization can become a bottleneck, reducing system scalability.

    Conclusion

    Synchronization is a vital concept in operating systems to ensure correct, safe, and efficient execution of concurrent processes and threads. By using mechanisms like locks, semaphores, monitors, condition variables, and read-write locks, operating systems manage access to shared resources and ensure that race conditions, deadlocks, and starvation do not occur. However, effective synchronization requires careful design to avoid performance bottlenecks and ensure system reliability and scalability.

    ← Previous topic 7
    Problems of Cooperative Processes
    Next topic 9 →
    Deadlocks

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    9mremaining
    1.5kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Operating Systems