Ch 11 Threads
Helps improve program throughput, facilitates resource sharing, and allows interactive programs to use multithreading to enhance response time.
A thread contains: a thread ID that identifies the thread, a set of register values, stack, scheduling priority and policy, signal mask, errno variable, and thread-specific data. All process information is shared among threads.
Creating Threads pthread_create
When creating threads, there is no guarantee which thread will execute first.
Thread Termination
If any thread in the process calls exit, _Exit, or _exit, the entire process will terminate.
Three ways to exit:
- Return from the start routine, where the return value is the thread’s exit code
- A thread can be canceled by other threads in the same process
- The thread calls pthread_exit
The calling thread will remain blocked until the specified thread calls pthread_exit, returns from the start routine, or is canceled.
If shared variables are allocated on the stack, the stack memory may be reused for other purposes after the thread exits. Therefore, it’s better to make shared variables global or allocate them using malloc.
Threads can request cancellation of other threads in the same process via pthread_cancel. This function does not block but merely makes the request.
Canceling the main thread of a process through pthread_cancel in a child thread will not cause the process to exit. The child thread will continue running even without the main thread. The process only exits when the last thread exits. This is fundamentally different from the case where returning from the process’s main function causes the process to exit and forcibly terminates child threads.
Thread Synchronization
Incrementing a variable requires:
- Reading from memory location into register
- Performing increment operation in register
- Writing new value back to memory
Spin Locks
Busy waiting
Mutexes
First spin for a period of time, then sleep after exceeding the count threshold. If the same mutex is locked twice, it will result in deadlock.
Reader-Writer Locks
Reader-writer locks Timed reader-writer locks: prevent getting stuck in permanent blocking state when acquiring reader-writer locks
Condition Variables
Allow threads to wait for specific conditions to occur in a non-competitive manner. Put in queue and sleep, wake up when appropriate conditions are met.
Barriers
Synchronization mechanism that coordinates multiple threads working in parallel, allowing each thread to wait until all cooperating threads reach a certain point.