27. Interlude: Thread API Flashcards
Describe the POSIX interface for thread creation
pthread_create(pthread_t thread, const pthread_attr_t attr, void *(start_routine)(void), void *arg);
*thread - pointer to strcture of type pthread_t
*attr - attributes the thread might have (stack size, priority, etc.)
start_routine - a pointer to function which takes void pointer and return void pointer
*arg - function arguments
Why does thread creation call uses void argument and void return value for function?
It allows us to pass and return any type of data
How do you wait for thread to complete? Describe call interface
int pthread_join(pthread_t thread, void **value_ptr);
thread - specify the thread to wait for
**value_ptr - pointer to return value we expect to get back
**value_ptr is an address of a pointer (i.e pointer to pointer) where we will put the returned pointer from thread
What is interface for lock and unlock?
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
What you need to do before using a lock?
It should be properly initialized. It can be done with following:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
or
pthread_mutex_init(&lock, NULL) - where the second argument is an optional set of attributes, NULL stands for defaults
What should be done after using the lock completely?
pthread_mutex_destroy()
What are other interfaces that can be used to acquite the lock?
int pthread_mutex_trylock(pthread_mutex_t *mutex); - return failure if lock is already held
int pthread_mutex_timedlock(pthread_mutex_t *mutex, struct timespec *abs_timeout) - returns after timeout or after acquiring the lock
What are conditional variables used for?
For cases when some kind of signaling should take place between threads, if one thread is waiting for another to do something before it can continue