Lecture 07 - Need to finish the bits on semaphores Flashcards
What are the three main ways in which a multi-threaded program can go wrong?
- Deadlock
- Race Conditions
- Starvation
What is the name given to source code that leads to a race condition?
A critical section
What is a race condition?
When two or more threads are simultaneously reading/working on the same data which can result in data becoming inconsistent, or overwritten.
Name two tools used to safeguard critical sections.
Mutexes and semaphores
What is a mutex?
A variable which can be locked.
How many threads can lock a mutex at once?
One
What happens when a thread tries to lock a mutex which is already locked by another thread?
It blocks until the mutex becomes unlocked.
What type is used to store mutexes?
pthread_mutex_t
What function initialises a mutex?
pthread_mutex_init
What is the function prototype for pthread_mutex_init?
int pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* attr);
How do you initialise a GLOBAL mutex?
pthread_mutex_t m = PTHREAD_MUTEX_INITIALISER;
What function destroys a mutex?
pthread_mutex_destroy
What is the function prototype for pthread_mutex_destroy?
int pthread_mutex_destroy(pthread_mutext_t* mutex);
What function is used to lock a mutex?
pthread_mutex_lock
What is the function prototype for pthread_mutex_lock?
int pthread_mutex_lock(pthread_mutex_t* mutex);
What function is used to unlock a mutex?
pthread_mutex_unlock
What is the function prototype for pthread_mutex_unlock?
int pthread_mutex_unlock(pthread_mutex_t* mutex);
What function locks a mutex only if it’s available?
trylock
What does trylock return if the mutex was successfully locked?
0
What does trylock return if the mutex was invalid?
EINVAL
What does trylock return if the mutex was busy?
EBUSY
What causes deadlock?
When two or more threads are waiting on each other’s resources.