Operating Systems
COMP 3430 Guderian
Copyright By PowCoder代写 加微信 powcoder
Where were we
We saw concurrent code can cause some issues New tool: pthread_mutex_t
Mutex – mutual exclusive lock
Posix gives us these tools to work with:
Posix gives us these tools to work with: pthread_mutex_t – mutex variable
Posix gives us these tools to work with:
pthread_mutex_t – mutex variable pthread_mutex_lock – stop, wait for exclusive access
Posix gives us these tools to work with:
pthread_mutex_t – mutex variable pthread_mutex_lock – stop, wait for exclusive access
pthread_mutex_unlock – free the lock when done
Posix gives us these tools to work with:
pthread_mutex_t – mutex variable pthread_mutex_lock – stop, wait for exclusive access
pthread_mutex_unlock – free the lock when done
pthread_mutex_trylock – non-blocking test of the lock
pthread_mutex_lock(&myLock); // my critical section pthread_mutex_unlock(&myLock);
pthread_mutex_lock(&myLock); // my critical section pthread_mutex_unlock(&myLock);
Try it! Fix thread_clobber.c
So, what did you lock
We want to lock as little as possible at at time
Did you lock the work, or did you lock the access/change
Locks serialize task
These tasks are no longer concurrent!
More later!
There are even more problems…
signaling threads What if our threads have nothing to do right now?
signaling threads
What if our threads have nothing to do right now? This is common!
signaling threads What if our threads have nothing to do right now?
This is common! Humans are slow
signaling threads What if our threads have nothing to do right now?
This is common! Humans are slow I/O slow
Condition variables
We can signal the threads that there is new work that needs to be consumed.
Posix gives us condition variables. Condition variables block a thread until it is signaled that it can continue.
Condition variables
We free the lock while we wait
pthread_mutex_lock(&signalLock); while(!signaled){
pthread_cond_wait(&signalAvailable, &signalLock);
printf(“%s got signaled\n”, threadName);
// I have been signaled, and I have the lock
signaled = false;
printf(“%s has got the lock\n”, threadName);
Why the while?
Change the clobber code to block until signaled Then, in main, signal your 2 threads to do the work!
Locks serialize access critical sections
If we have time…
How does a signal to a thread compare to a process?
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com