An introduction to threads, their functions, sharing mechanisms, differences from processes, and basic thread functions such as creation and waiting for termination. It also mentions the advantages and disadvantages of thread programming and the posix standard for threading (pthreads).
Download Understanding Threads: Functions, Sharing, and Differences from Processes and more Slides Computer Programming in PDF only on Docsity!
Week 11 Topics
Threads
Basic thread functions
Some more thread functions
Thread-specific data
Mutual exclusion
Conditional variables
Threads
A thread is an independent sequence of execution of program code inside a process
A thread is often called a lightweight process
But it is NOT a process
It is something smaller than a process
The process context includes
Memory, instruction, program counter, stack pointer, registers, open file descriptor, etc.
A thread has less
Program counter, a stack, and a set of registers, etc.
Threads vs Processes
Advantages of threads
It is less expensive to create a thread
Inter-thread communication is much simpler and cheaper than inter-process communication
Thread programming can be dangerous
It is easy to make mistakes
Some system functions may break with threads
Basic thread functions
Thread creation int pthread_create(pthread_t *thread, constpthread_attr_t *attr, void (start_routine)(void *),void * arg) - Thread attributes (stack size, scheduling policy) can be modified - Use NULL for default - Returns 0 if successful, and an error number if it fails - EAGAIN: System lacks resources - EINVAL: Invalid attribute - EPERM: Caller does not have appropriate permission - Pthread functions return error values - They do not set errno - New thread executes the function given by start_routine - arg is the argument to this function - The thread ID is stored in *thread