Intro to Threads
Notes
- I needed threads to make some demos a little more palatable.
- This is (part of) chapter 4 of the book.
- A thread is a lightweight process
- Originally process threads
- I knew my process would not use the entire timeslice, but I had multiple things to do
- So I divide my process into tasks, or threads
- And manage the scheduling myself.
- Everything is manage in user space, not in kernel space
- These are called user threads
- Later this was migrated to the OS.
- Today a thread is the lowest or basic unit of execution.
- Threads are all started, and live within a single process.
- Threads share:
- code segment
- data segment (global variables)
- heap
- Many things like files, signal masks, ...
- Threads do not share:
- Threads can execute concurrently
- The main advantages of threads over processes
- Automatically shared memory via global variables and memory allocated on the heap.
- It is much easier, and faster to create a thread than a new process.
- Since they share memory, threads are less resource intensive
- Threads may be more responsive than processes, again a resource thing.
- One must be extremely careful however, threads share memory so ...
- Many traditional unix calls are not reentrant, or can not be run safely by multiple threads.
-
int rand(void) is an example
- Rand is normally Xn+1 = (aXn+c)%m
- Where X is stored in a shared memory location.
- So we have a problem when multiple threads try to access X at the same time.
-
int rand_r(unsigned int * seedp) is the reentrant version
- This is true of many functions.
- Most are
function_r
- And require you to pass the "state" variable that is stored globally.
- This is enought to get us stared, we will look at more details with threads later.