Flashcards in chapter 26: threads intro, concurrency: an intro Deck (12):
thread is very much like a process but what is the difference?
threads share the same address space and thus can access the same data (heap and global variables)
what does a thread have?
it has a Program counter(PC) that tracks where the program is fetching instructions from.
it has its own set of registers used for computation
context switch between threads
is shares the same address space so when its switched it remains in the same address space.
with processes, we saved states to PCB(process control block)
with threads we need TCB(thread control blocks to store the state of each thread of a process
difference between single threaded and multithreaded address spaces
with single threaded process, code and heap on top and stack starts from the bottom growing upwards
with multi, we have blocks of memory allocated for each thread stack in the memory. (thread-local storage)
ruins our beautiful structure. but its usually ok as stacks dont grow that large usually
why use threads?
at least 2 major reasons
1. parallelism - speeding up the process
2. avoid blocking program progress due to slow I/O. one thread waits, the other threads can do their thang
note: can be done with process, but it is better using thread because same address space
how do multiple threads run?
what runs next is determined by the OS scheduler and it is hard to know what will run at any given moment
what is the problem with shared data between threads?
T1 increments the counter by 1 to 51. it loads it into the register eax. now, a timer interrupt goes off, the OS saves the state of the currently running thread to the TCB.
T2 is chosen to run, gets the value and puts it into the eax. the value of counter is still 50 and T2 has eax=50.
T2 increments by 1 making counter=eax=51.
context switch occurs, T1 resumes running. counter is set to 51 again. counter should =52.
this is a race condition.
uncontrolled scheduling problem?
race condition may happen with untimely context switches between thread. went from deterministic computation to indeterminate - not know what the output will be.
this is because multiple threads executing the critical section at the same time.
what do we want in multithreaded programs?
Mutual Exclusion - when one thread is executing within critical section(CS) the others will be prevented from doing so.
the wish for atomicity
one way to solve this problem is to do everything in a single step. all or nothing.
another problem: waiting for another thread to finish
another problem is when a thread needs to wait for another to complete to continue running their part. this is supported using conditional variables(CV)