Threads Flashcards
What is a thread?
A path execution
What is the default c/c++ thread?
main thread
How can you create a thread in c?
pthread_create( &thr_id, attr, func, arg )
What does every thread have its own of?
◼ Stack
◼ PC – Program counter
◼ Set of registers
◼ State
Function calls, local vars
What are some common examples of using multiple threads?
Server, serving multiple requests. Using multiple cores of the cpu
What are the advantages of using threads over processes?
Faster creation, faster context switch, faster communication.
What are the disadvantages of using threads and not processes?
Less robust, a crash brings whole application down. More synchronization problems because shared global variables.
What is an Atomic Section (Critical)?
A portion of the code that only one thread should execute on.
How do you use a mutex lock?
pthread_mutex_lock(&mutex);
int tmp = counter;
tmp=tmp+1;
counter=tmp;
pthread_mutex_unlock(&mutex);
What happens when you use different mutex locks on two different sections of code?
Sequences can interleave each other.
What are the two approaches to implementing mutex locks?
Disable interupts, Spin Locks
Why isn’t disabling interrupts for mutex locks popular?
Other interrupts may be lost, only available in Kernel mode
How do spin locks work?
Make the thread “spin” busy waiting until unlocked.
What is the difference between our basic spin lock and an actual mutex lock?
Spin lock wastes cpu cycles. Mutex lock just puts thread in wait state.
What happens to threads when fork is called?
They are not duplicated, unless it is the thread calling fork.
Why is it bad to mix threads and forking?
Locking can get blocked if tried in child process.
What is a Race Condition?
When multiple threads edit the data structure at the same time.
What is a semaphore?
A generalization of mutexes. Allows a specific number of threads between mutexes.
What is the initial counter of a semaphore?
0 or greater
What are semaphores used for?
Mutex lock (init to 1), N resource case. Waiting for an event (init to 0)
How to decrement a semaphore?
sema_wait(sema_t *sem)
How to increment a semaphore?
sema_post(sema_t *sem)
Why must sema_wait be done outside of the mutex_lock/unlock section?
If you lock then wait, the value will never change so it won’t pass the wait.
What are Read/Write locks?
Allow multiple lookups at the same time but only one write.