Threads Case Study: PThreads
Creation
To represent the thread data structure, PThread supports a pthread_t
data type in C.
The data type contains an ID, execution state, and any other information that's relevant to the thread.
Attributes
Pthread attributes allow us to specify the stack size, scheduling policy, inheritance, joinablility, priority, and system process scope of the newly created pthread. If NULL
is passed in, all these attributes will be instantiated with some default values. There are multiple API calls available to pthread attributes.
Detachable
In pthreads, the default behavior of thread creation is joinable. With joinable threads, the parent thread creates children threads and can join them at a later time. The parent thread will not terminate until the children threads have completed their execution and have been joined via the explicit join operation.
In the event of parent thread exits early and fails to terminate children threads properly, the children threads can become zombie threads and eat up memory because it is expecting to join the parent before releasing its resources. However, if we specify the thread to be detachable, the thread can continue execute and release its resource upon termination.
Here's an example of detached threads.
Mutexes
The mutex type is represented by the following construct.
While the lock and unlock operation will have the following signature.
Here's an example of thread safe insertion to a list.
Other Mutex Operations
Mutex needs to be initialized. The attribute specifies the mutex behavior when it is shared among processes.
We can also check a mutex and see if it is locked. If it is locked, the check function will return immediately instead of being blocked.
Finally we need to destroy the mutex to free up memory.
Mutex Safety
Shared data should always be access through a single mutex.
Mutex scope must be visible to all threads.
We should globally order locks. This is to ensure there is no deadlock in the operations.
Condition Variables
The condition variable type is represented by the following construct.
The wait operation takes two arguments, the condition and the mutex. A thread that is entering the wait operation will automatically release the mutex and place itself on the wait queue that's associated with the condition variable. When the thread is woken up, it will automatically re-acquire the mutex before exiting the wait operation.
Here are signal and broadcast operations.
Other Cond Operations
Cond Safety
Do not forget to notify waiting threads.
When in doubt, use broadcast.
You do not need a mutex to signal or broadcast.
Last updated