SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
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

Más contenido relacionado

Más 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
 

Más 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

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Último (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

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