Concurrency

Why concurrency?

Parallel hardware

Inter-process communication

Reminder: What is a thread

Reminder: What is a process

I/O vs Communication

Direction

Communication example

Files

A file-based IPC example

Directories

Pipes

UNIX and pipes

Sockets

Shared memory

Message passing

Synchronizace

Shared variables

Shared heap variable

void *thread( int *x ) { *x = 7; }
int main()
{
    pthread_t id;
    int *x = malloc ( sizeof( int ) );
    pthread_create( &id, NULL, thread, x );
}

Race condition: example

int i = 0;
void thread1() { i = i + 1; }
void thread2() { i = i - 1; }

Race on variable

a₀ ← load i  | b₀ ← load i
a₁ ← a₀ + 1  | b₁ ← b₀ - 1
store a₁ i   | store b₁ i

Critical section

Race condition: definition

Races in filesystem

Mutual exclusion

Semaphore

Monitors

Condition variables

Spinlocks

Suspending mutexes

Condition variables revisited

Barrier

Reader and writers

Read-copy-update

Deadlocks and starvation

Dining philosophers

Shared recources

Network-based sharing

Locks as recources

Preemptable resources

Non-preemptable resources

Resource aquisition

Waiting

Resource deadlock

Resource deadlock conditoins

  1. mutual exclusion
  2. hold and wait condition
  3. non-preemtability
  4. circular wait

Deadlock je možný pouze pokud jsou všechny 4 možné.

Non-resource deadlocks

Example: pipe deadlock

Deadlock: do we care?

Deadlock detection

Deadlock recovery

Deadlock avoidance

Deadlock prevention

Prevention via spooling

Prevention via reservation

Prevention via ordering

Livelock

Starvation