Threads
“Lightweight Processes”
Resources
- Every thread belongs to one process
- Resources between threads of a Process
- Shared
- Text (Instructions)
- Data (Constants/Statics)
- Heap
- Open Files
- Signals
- Pending alarms
- Separate
- Registers
- Stack
- Program counter
- Scheduler State
- Shared
Why
- Usage
- Avoid wasting memory with repeated information
- Break up complicated tasks into simpler ones
- Improve efficiency via parallelism
- Advantages over Processes
- Lower memory cost (shared segments)
- Information sharing (shared data)
- Reduced creation, destruction time (no need to copy memory)
fork
is an expensive system call
- Reduced context switch time (when within the same process)
pthread
Library
- User space threading library
pthread_create
- does not promise immediate execution
- termination
- the main thread terminating terminates all threads
- any thread calling
exit
terminates the whole process pthread_exit
only terminates the current thread (even if that thread is the main thread)
pthread_join
- blocks until a different thread ends
- if the thread to wait on has already terminated, it does not block
User-Space vs Kernel-Space
- User-Space
- Managed by user library (within a process)
- OS-Independent
- Syscalls block all process threads
- Process threads in one CPU
- Does not allow for concurrency
- Managed by procedure calls (cheap)
- Switching between threads is very fast
- The advantage is sharing resources
- Kernel-Space
- Managed by a system library
- OS-Specific
- Syscalls block calling thread
- Process threads in multiple CPUs
- Allows for concurrency
- Managed by system calls (expensive)
- Switching between threads is slower
- The advantage is sharing resources and concurrency
- Hybrid
- We can mix to try to get the best of both worlds
- However, this is very complex so best only used if necessary