CS139-lecture-20211021

Process synchronization #

image_2021-10-21-13-34-33 image_2021-10-21-13-34-40 image_2021-10-21-13-34-45

Race condition #

image_2021-10-21-13-34-50 image_2021-10-21-13-35-04 image_2021-10-21-13-35-09 image_2021-10-21-13-36-09

Critical section and mutual exclusion #

image_2021-10-21-13-37-17

In the above code examples, the counter++ and counter-- are considered a critical section.

image_2021-10-21-13-38-05 image_2021-10-21-13-40-00 image_2021-10-21-13-40-06 image_2021-10-21-13-40-11 image_2021-10-21-13-40-34 image_2021-10-21-13-40-57 image_2021-10-21-13-43-30

How to implement mutual exclusion #

image_2021-10-21-13-43-40 image_2021-10-21-13-43-45 image_2021-10-21-13-44-09

Note: This solution isn’t fully correct.
producer:
    while (lock == 0)
        lock = 1
        put
        lock = 0

consumer:
    while (lock == 0)
        lock = 1
        fetch
        lock = 0

The problem with this code is that if the OS does a context switch during a critical section, it can create an error.

image_2021-10-21-13-52-42 image_2021-10-21-13-55-12

One solution is to disable interrupts.

image_2021-10-21-13-55-27 image_2021-10-21-13-55-31

Sync hardware, spin locks and compare-and-swap #

image_2021-10-21-13-59-36 image_2021-10-21-14-01-51 image_2021-10-21-14-09-56 image_2021-10-21-14-18-04 image_2021-10-21-14-19-45

Mutex locks #

Mutex locks allow the OS to provide a mutual exclusion as a service.

image_2021-10-21-14-20-05 image_2021-10-21-14-21-32 image_2021-10-21-14-23-46

Semaphores #

image_2021-10-21-14-23-56

A semaphore is simply a non-negative interger that has two valid operations.

image_2021-10-21-14-26-59 image_2021-10-21-14-30-05 image_2021-10-21-14-32-26 image_2021-10-21-14-41-34 image_2021-10-21-14-44-10