Two Types of Concurrency
Message Passing
Each procedure has its own private memory
Interaction via message
ASYCHRONOUS, DISTRIBUTED
Shared Memory
Each procedure has access to the shared memory.
SYCHRONOUS, CENTRALIZED
Multi-threaded Program
#include<pthread.h>
pthread_create: create a thread.
pthread_join: wait until the thread terminate.
Thread Interleaving
If there are \(n\) threads, each thread has \(m\) statement.
The number of possible permutation of execution of statements are
Safety and Concurrency Error
Race Condition
Similar to write-after-read in computer architecture.
Example:
The thread first read the global variable cnt, write cnt+1 to cnt.
If we create two threads, this may happen:
cnt=0 initially
- thread 1 read
cnt - thread 2 read
cnt - thread 1 write
cnt+1=1tocnt - thread 2 write
cnt+1=1tocnt
The expected value of cnt is 2. Assertion failed.
Deadlock
How to solve race condition? Introduce mutex to lock the cnt.
But sometimes deadlock will introduce deadlock!
Example:
Thread A:
- Lock
a - Lock
b - Do something
- Release
b - Release
a
Thread B:
- Lock
b - Lock
a - Do something
- Release
a - Release
b
If we run both threads at the same time, this may happen:
- Thread A locks
a - Thread B locks
b - Thread A waits for
band Thread B waits fora. DEADLOCK!
Concurrency and Complex Systems
A concurrency program is a complex system.
Local VS Global behavior