One process can have many threads, knows as a multithreaded process
Threads in the same process share
Memory context: Text, Data, Heap
OS context: PID, files etc.
They do not share
Thread ID
Registers
Stack pointer (Each thread gets allocated a part of the stack, but all from the same memory)
Process context switch vs thread switch
Process context switch: OS context, hardware context, memory context
Thread switch (within same process): Hardware context: registers, SP & FP
Benefits
No expensive fork operations duplicating context and context switching
Easier communication because they access the same memory space
Responsive, thread switching has very low overhead
Scalable, multithreaded program can take advantage of multiple CPUs
Problems
Concurrency: parallel execution of threads, may cause parallel syscalls
Process behaviour: e.g. fork() behaviour, thread calling exit(), exec()
Implementations
User thread
Implemented as a user library (runtime that manages threads within the process)
Kernel is not aware of the threads in the process
Advantages: Multithreading on any os; Thread operations are just library calls; More flexible
Disadvantages: Scheduling is done at process level, so one thread blocking = process blocked = all threads blocked
Kernel thread
Thread is implemented in the OS, thread operations handled by syscalls
Thread-level scheduling possible
Kernel can use threads for its own execution
Advantages: Kernel can schedule on thread-level, more than 1 thread in the same process can run simultaneously on multiple CPUs
Disadvantages: Thread operation is now a slower and more resource intensive syscall; Less flexible, one implementation used by all programs
Hybrid Thread Model
Both kernel and user threads
OS schedules on kernel threads only
User threads can bind to a kernel thread e.g. 4 user threads, 3 kernel threads, program can assign user threads to kernel threads
Hardware Multithreading
Modern processors have multiple sets of registers, allowing threads to run natively and in parallel on one CPU
Known as simultaneous multi-threading (SMT), intel calls it hyperthreading
Posix Threads
#include <pthread.h>
gcc XXXX.c –lpthread (system dependent)
int pthread_create(pthread_t* tidCreated, const pthread_attr_t* threadAttributes, void* (*startRoutine) (void*), void* argForStartRoutine);
int pthread_exit(void* exitValue);
void* abc ( void* arg ) { // something}
int main ()
pthread_t tid [ 5 ]; //5 thread ids
int i;
for (i = 0 ; i < 5 ; i ++ )
pthread_create ( & tid [i], NULL , abc, NULL );
for (i = 0 ; i < 5 ; i ++ ) //Wait for all threads
pthread_join ( tid [i], NULL );
// use result
}