<

Lecture #6

Administrivia

Our Story So Far (Abbreviated)

More About Pointers

Observations:

struct S1 {
    char c1;
    char c2;
    int i;
};

struct S2 {
    char c1;
    int i;
    char c2;
};

Note:

Critical Section

Synchronization

canonical example:

// process/thread 1:
current_balance = account.get_balance()
new_balance = current_balance + paycheck
account.update(new_balance)

// process/thread 2:
current_balance = account.get_balance()
new_balance = current_balance - withdrawl
account.update(new_balance)

TODO: diagram

Synchronization techiques

Software Solution: Decker's Algorithm

TODO: diagram & pseudocode

```

```

Hardware Support

Semaphore vs. Mutex

Semaphores

Pthread Mutex

#include <pthread.h>

int pthread_mutex_init(
    pthread_mutex_t *mutex,
    const pthread_mutex_attr_t *attr
);
// if attr is NULL, use default values

pthread_mutex_lock(pthread_mutex_t *mutex);

pthread_mutex_unlock(pthread_mutex_t *mutex);

Condition Variables

example: producer-consumer pair: producer and consumer must have exclusive access (mutual exclusion) to buffer, but consumer must also wait until the buffer is not empty to proceed

polling:

while !done
   get mutex
   if condition
      process()
      done = true
   release mutex

condition varible:

while !done
   get mutex lock
   while !condition
      wait on condition variable
   if condition
      process()
      done = true
   release lock

Pthread Condition Variables

int pthread_cond_init(
    pthread_cond_t *cond,
    const phtread_condattr_t *attr  // NULL for default settings
)

int pthread_cond_signal(pthread_cond_t *cond);

int pthread_cond_wait(
    pthread_cond_t *cond,
    pthread_mutex_t *mutex
);

Semaphores (Again)

Monitors

can implement monitor in C++ using RAII (Resource Allocation Is Initiation):

{
  // unprotected code
  {
    // more unprotected code (optional)
    Monitor m();  // constructor acquires lock
    // protected code
    m.wait_for(signal_var)  // optional
    // more protected code
   }  // destructor releases lock, called automagically on object m when leaving scope
   // even more unprotected code
}