Note

Why do we need this? We have 2 threads accessing the same memory and trying to share information.

This is important for things like global variables where two threads are accessing that variable at the same time.

Primitives

Problems

Dining Philosophers

  • There are n philosophers in a room
  • They are seated around a round table with n bowls of rice and one chopstick between each bowl
  • A philosopher requires 2 chopstick to eat
  • Philosophers are either eating or thinking
  • If they don’t eat, they starve

There are 2 problems here:

  • Deadlock: If everyone picks up one chopstick, no one can eat and everyone needs what everyone else has
  • Starvation:
    • If two philosophers never give up their chopsticks, that leaves 1 free and 3 philosophers

You need an arbitrator (scheduler) or to have more resources.

Readers-Writers

  • Consider a shared resource
  • Any number of readers can access it at one time since they do not modify it
  • Only one writing at a time can make changes
    • When a writer is accessing the resource, nothing else can
    • When someone is reading, no one can write

Here, we need a read-write lock which are binary semaphores that reads do not decrement but writers do.

See