SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler offline
Operating Systems
          CMPSCI 377
        Synchronization
                   Emery Berger
University of Massachusetts Amherst




UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
Synchronization

    Threads must ensure consistency


        Else: race condition
    

        (non-deterministic result)
        Requires synchronization operations
    

    How to write concurrent code


    How to implement synch. operations





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   2
Synchronization – Motivation
    “The too much milk problem”





    Model of need to synchronize activities




      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   3
Synchronization Terminology

Mutual exclusion (“mutex”)
   – prevents multiple threads from entering
Critical section
   – code only one thread can execute at a time
Lock
  – mechanism for mutual exclusion
       Lock on entering critical section, accessing shared
   

       data
       Unlock when complete
   

       Wait if locked
   




       UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   4
Solving the Too Much Milk Problem
    Correctness properties


        Only one person buys milk
    

          Safety: “nothing bad happens”

        Someone buys milk if you need to
    

          Progress: “something good eventually happens”




    First: use atomic loads & stores as building blocks


        “Leave a note” (lock)
    

        “Remove a note” (unlock)
    

        “Don’t buy milk if there’s a note” (wait)
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   5
Too Much Milk: Solution 1


                                                 thread B
thread A
if (no milk && no note)                          if (no milk && no note)
  leave note                                       leave note
  buy milk                                         buy milk
  remove note                                      remove note




    Does this work?much milk
                too


      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   6
Too Much Milk: Solution 2


Idea: use labeled notes

                                               thread B
thread A
leave note A                                   leave note B
if (no note B)                                 if (no note A)
  if (no milk)                                   if (no milk)
    buy milk                                       buy milk
remove note A                                  remove note B


                          oops – no milk

    UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   7
Too Much Milk: Solution 3


Idea: wait for the right note

                                                 thread B
thread A
leave note A                                     leave note B
while (note B)                                   if (no note A)
  do nothing                                       if (no milk)
if (no milk)                                         buy milk
  buy milk                                       remove note B
remove note A

    Exercise: verify this

      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   8
Too Much Milk: Solution 3


Possibility 1: A first, then B

                                                thread B
thread A
leave note A                                    leave note B
while (note B)                                  if (no note A)
  do nothing                                      if (no milk)
if (no milk)                                        buy milk
  buy milk                                      remove note B
remove note A

    OK

     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   9
Too Much Milk: Solution 3


Possibility 2: B first, then A

                                                thread B
thread A
leave note A                                    leave note B
while (note B)                                  if (no note A)
  do nothing                                      if (no milk)
if (no milk)                                        buy milk
  buy milk                                      remove note B
remove note A

    OK

     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   10
Too Much Milk: Solution 3


Possibility 3: Interleaved – A waits & buys

                                                thread B
thread A
leave note A                                    leave note B
while (note B)                                  if (no note A)
  do nothing                                      if (no milk)
if (no milk)                                        buy milk
  buy milk                                      remove note B
remove note A

    OK

     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   11
Too Much Milk: Solution 3


Possibility 4: Interleaved – A waits, B buys

                                                thread B
thread A
leave note A                                    leave note B
while (note B)                                  if (no note A)
  do nothing                                      if (no milk)
if (no milk)                                        buy milk
  buy milk                                      remove note B
remove note A

    OK

     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   12
Too Much Milk: Solution 3
Solution 3:
  “Thread A waits for B, otherwise buys”

    Correct – preserves desired properties


        Safety: we only buy one milk
    

        Progress: we always buy milk
    

    But…





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   13
Problems with this Solution
    Complicated


        Difficult to convince ourselves that it works
    

    Asymmetrical


        Threads A & B are different
    

        Adding more threads = different code for each thread
    

    Poor utilization


        Busy waiting – consumes CPU, no useful work
    

    Possibly non-portable


        Relies on atomicity of loads & stores
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   14
Language Support
    Synchronization complicated


    Better way – provide language-level

    support
        Higher-level approach
    

        Hide gory details in runtime system
    



    Increasingly high-level approaches:


        Locks, Atomic Operations
    

        Semaphores – generalized locks
    

        Monitors – tie shared data to
    
        synchronization
        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   15
Locks
    Provide mutual exclusion to shared data

    via two atomic routines
        acquire – wait for lock, then take it
    

        release – unlock, wake up waiters
    



    Rules:


        Acquire lock before accessing shared data
    

        Release lock afterwards
    

        Lock initially released
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   16
Pthreads Syntax
    POSIX standard for C/C++


    Mutual exclusion locks


        Ensures only one thread in critical section
    



    pthread_mutex_init (&l);
    …

    pthread_mutex_lock (&l);
    update data; /* critical section */
    pthread_mutex_unlock (&l);

        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   17
Pthreads API




   UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   18
Too Much Milk: Locks



thread A                                         thread B
p_m_lock(&l)                                     p_m_lock(&l)
if (no milk)                                     if (no milk)
  buy milk                                         buy milk
p_m_unlock(&l)                                   p_m_unlock(&l)




    Clean, symmetric - but how do we implement it?

      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   19
Implementing Locks
    Requires hardware support (in general)


    Can build on atomic operations:


        Load/Store
    

        Disable interrupts
    

              Uniprocessors only
          


        Test & Set, Compare & Swap
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   20
Disabling Interrupts
    Prevent scheduler from switching threads


    in middle of critical sections
        Ignores quantum expiration (timer interrupt)
    

        No handling I/O operations
    

              (Don’t make I/O calls in critical section!)
          




    Why not implement as system call?





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   21
Disabling Interrupts
Class Lock {
  private int value;
  private Queue q;

 Lock () {
   value = 0; q = empty;
 }

                                              public void release () {
 public void acquire () {
                                                disable interrupts;
   disable interrupts;
                                                if (q not empty) {
   if (value == BUSY) {
                                                  thread t = q.pop();
     add this thread to q;
                                                  put t on ready queue;
     enable interrupts;
                                                }
     sleep();
                                                value = FREE;
   } else {
                                                enable interrupts;
     value = BUSY;
                                              }
   }
   enable interrupts;
 }




     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   22
Locks via Disabling Interrupts




   UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   23
Summary

    Communication between threads:


    via shared variables
    Critical sections = regions of code that


    modify or access shared variables
    Must be protected by synchronization


    primitives that ensure mutual exclusion
        Loads & stores: tricky, error-prone
    

        Solution: high-level primitives (e.g., locks)
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   24
The End




   UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   25

Mais conteúdo relacionado

Mais de Emery Berger

Doppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierDoppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierEmery Berger
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingEmery Berger
 
Programming with People
Programming with PeopleProgramming with People
Programming with PeopleEmery Berger
 
Stabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationStabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationEmery Berger
 
DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)Emery Berger
 
Operating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsOperating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsEmery Berger
 
Operating Systems - File Systems
Operating Systems - File SystemsOperating Systems - File Systems
Operating Systems - File SystemsEmery Berger
 
Operating Systems - Networks
Operating Systems - NetworksOperating Systems - Networks
Operating Systems - NetworksEmery Berger
 
Operating Systems - Queuing Systems
Operating Systems - Queuing SystemsOperating Systems - Queuing Systems
Operating Systems - Queuing SystemsEmery Berger
 
Operating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingOperating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingEmery Berger
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - ConcurrencyEmery Berger
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationEmery Berger
 
Processes and Threads
Processes and ThreadsProcesses and Threads
Processes and ThreadsEmery Berger
 
Virtual Memory and Paging
Virtual Memory and PagingVirtual Memory and Paging
Virtual Memory and PagingEmery Berger
 
Operating Systems - Virtual Memory
Operating Systems - Virtual MemoryOperating Systems - Virtual Memory
Operating Systems - Virtual MemoryEmery Berger
 
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsMC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsEmery Berger
 
Vam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorVam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorEmery Berger
 
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementQuantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementEmery Berger
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without PagingEmery Berger
 
DieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesDieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesEmery Berger
 

Mais de Emery Berger (20)

Doppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierDoppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language Barrier
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic Multithreading
 
Programming with People
Programming with PeopleProgramming with People
Programming with People
 
Stabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationStabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance Evaluation
 
DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)
 
Operating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsOperating Systems - Advanced File Systems
Operating Systems - Advanced File Systems
 
Operating Systems - File Systems
Operating Systems - File SystemsOperating Systems - File Systems
Operating Systems - File Systems
 
Operating Systems - Networks
Operating Systems - NetworksOperating Systems - Networks
Operating Systems - Networks
 
Operating Systems - Queuing Systems
Operating Systems - Queuing SystemsOperating Systems - Queuing Systems
Operating Systems - Queuing Systems
 
Operating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingOperating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel Computing
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - Concurrency
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced Synchronization
 
Processes and Threads
Processes and ThreadsProcesses and Threads
Processes and Threads
 
Virtual Memory and Paging
Virtual Memory and PagingVirtual Memory and Paging
Virtual Memory and Paging
 
Operating Systems - Virtual Memory
Operating Systems - Virtual MemoryOperating Systems - Virtual Memory
Operating Systems - Virtual Memory
 
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsMC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
 
Vam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorVam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory Allocator
 
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementQuantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without Paging
 
DieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesDieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe Languages
 

Último

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 

Último (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 

Operating Systems - Synchronization

  • 1. Operating Systems CMPSCI 377 Synchronization Emery Berger University of Massachusetts Amherst UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
  • 2. Synchronization Threads must ensure consistency  Else: race condition  (non-deterministic result) Requires synchronization operations  How to write concurrent code  How to implement synch. operations  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 2
  • 3. Synchronization – Motivation “The too much milk problem”  Model of need to synchronize activities  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 3
  • 4. Synchronization Terminology Mutual exclusion (“mutex”) – prevents multiple threads from entering Critical section – code only one thread can execute at a time Lock – mechanism for mutual exclusion Lock on entering critical section, accessing shared  data Unlock when complete  Wait if locked  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 4
  • 5. Solving the Too Much Milk Problem Correctness properties  Only one person buys milk   Safety: “nothing bad happens” Someone buys milk if you need to   Progress: “something good eventually happens” First: use atomic loads & stores as building blocks  “Leave a note” (lock)  “Remove a note” (unlock)  “Don’t buy milk if there’s a note” (wait)  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 5
  • 6. Too Much Milk: Solution 1 thread B thread A if (no milk && no note) if (no milk && no note) leave note leave note buy milk buy milk remove note remove note Does this work?much milk too  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 6
  • 7. Too Much Milk: Solution 2 Idea: use labeled notes thread B thread A leave note A leave note B if (no note B) if (no note A) if (no milk) if (no milk) buy milk buy milk remove note A remove note B oops – no milk UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 7
  • 8. Too Much Milk: Solution 3 Idea: wait for the right note thread B thread A leave note A leave note B while (note B) if (no note A) do nothing if (no milk) if (no milk) buy milk buy milk remove note B remove note A Exercise: verify this  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 8
  • 9. Too Much Milk: Solution 3 Possibility 1: A first, then B thread B thread A leave note A leave note B while (note B) if (no note A) do nothing if (no milk) if (no milk) buy milk buy milk remove note B remove note A OK  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 9
  • 10. Too Much Milk: Solution 3 Possibility 2: B first, then A thread B thread A leave note A leave note B while (note B) if (no note A) do nothing if (no milk) if (no milk) buy milk buy milk remove note B remove note A OK  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 10
  • 11. Too Much Milk: Solution 3 Possibility 3: Interleaved – A waits & buys thread B thread A leave note A leave note B while (note B) if (no note A) do nothing if (no milk) if (no milk) buy milk buy milk remove note B remove note A OK  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 11
  • 12. Too Much Milk: Solution 3 Possibility 4: Interleaved – A waits, B buys thread B thread A leave note A leave note B while (note B) if (no note A) do nothing if (no milk) if (no milk) buy milk buy milk remove note B remove note A OK  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 12
  • 13. Too Much Milk: Solution 3 Solution 3: “Thread A waits for B, otherwise buys” Correct – preserves desired properties  Safety: we only buy one milk  Progress: we always buy milk  But…  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 13
  • 14. Problems with this Solution Complicated  Difficult to convince ourselves that it works  Asymmetrical  Threads A & B are different  Adding more threads = different code for each thread  Poor utilization  Busy waiting – consumes CPU, no useful work  Possibly non-portable  Relies on atomicity of loads & stores  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 14
  • 15. Language Support Synchronization complicated  Better way – provide language-level  support Higher-level approach  Hide gory details in runtime system  Increasingly high-level approaches:  Locks, Atomic Operations  Semaphores – generalized locks  Monitors – tie shared data to  synchronization UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 15
  • 16. Locks Provide mutual exclusion to shared data  via two atomic routines acquire – wait for lock, then take it  release – unlock, wake up waiters  Rules:  Acquire lock before accessing shared data  Release lock afterwards  Lock initially released  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 16
  • 17. Pthreads Syntax POSIX standard for C/C++  Mutual exclusion locks  Ensures only one thread in critical section  pthread_mutex_init (&l); … pthread_mutex_lock (&l); update data; /* critical section */ pthread_mutex_unlock (&l); UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 17
  • 18. Pthreads API UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 18
  • 19. Too Much Milk: Locks thread A thread B p_m_lock(&l) p_m_lock(&l) if (no milk) if (no milk) buy milk buy milk p_m_unlock(&l) p_m_unlock(&l) Clean, symmetric - but how do we implement it?  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 19
  • 20. Implementing Locks Requires hardware support (in general)  Can build on atomic operations:  Load/Store  Disable interrupts  Uniprocessors only  Test & Set, Compare & Swap  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 20
  • 21. Disabling Interrupts Prevent scheduler from switching threads  in middle of critical sections Ignores quantum expiration (timer interrupt)  No handling I/O operations  (Don’t make I/O calls in critical section!)  Why not implement as system call?  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 21
  • 22. Disabling Interrupts Class Lock { private int value; private Queue q; Lock () { value = 0; q = empty; } public void release () { public void acquire () { disable interrupts; disable interrupts; if (q not empty) { if (value == BUSY) { thread t = q.pop(); add this thread to q; put t on ready queue; enable interrupts; } sleep(); value = FREE; } else { enable interrupts; value = BUSY; } } enable interrupts; } UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 22
  • 23. Locks via Disabling Interrupts UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 23
  • 24. Summary Communication between threads:  via shared variables Critical sections = regions of code that  modify or access shared variables Must be protected by synchronization  primitives that ensure mutual exclusion Loads & stores: tricky, error-prone  Solution: high-level primitives (e.g., locks)  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 24
  • 25. The End UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 25