chapter 27 - interlude: thread API Flashcards
How do you create a new thread in POSIX?
Use pthread_create
What does the fourth argument of pthread_create() do?
It passes a void* argument to the new thread’s function - allowing any type of data to be passed
How do you wait for a thread to finish in POSIX?
Use pthread_join(pthread_t thread, void **retval);
Why should you not return a pointer to a stack variable from a thread?
Because the stack is destroyed when the thread ends — leading to undefined behavior
What should you pass to pthread_join() if you don’t care about the return value?
NULL
What functions are used to protect critical sections in pthreads?
pthread_mutex_lock()
pthread_mutex_unlock()
What is pthread_mutex_trylock() used for?
It tries to acquire the lock without blocking — returns immediately if the lock is bus
What is pthread_mutex_timedlock() used for?
Waits for a lock up to a specified timeout
What is a condition variable used for in pthreads?
To allow threads to wait for a condition to become true — enables signaling between threads
What do you need to include and link to use pthreads in C?
Include <pthread.h></pthread.h>
Compile with the -pthread flag