first commit
This commit is contained in:
76
CS4210/Homework 1/answers.txt
Normal file
76
CS4210/Homework 1/answers.txt
Normal file
@@ -0,0 +1,76 @@
|
||||
Jose Caban
|
||||
gtg184g
|
||||
CS4210 HW#1
|
||||
|
||||
Question 1:
|
||||
-----------
|
||||
|
||||
struct RecMutex {
|
||||
pthread_mutex_t mutex;
|
||||
pthread_cond_t locked;
|
||||
int lock;
|
||||
int owner;
|
||||
};
|
||||
|
||||
int rec_mutex_lock(RecMutex *rmutex) {
|
||||
|
||||
//CurrentThread is owner, increment lock
|
||||
if (rmutex->owner == CurrentThread()) {
|
||||
rmutex->lock++;
|
||||
return 0;
|
||||
} else {
|
||||
//Lock the mutex
|
||||
pthread_mutex_lock(&(rmutex->mutex));
|
||||
|
||||
//Wait until the lock is free
|
||||
while (rmutex->lock != 0) {
|
||||
pthread_cond_wait( &(rmutex->locked), &(rmutex->mutex) );
|
||||
}
|
||||
|
||||
//Set structure paramaters
|
||||
rmutex->owner = CurrentThread();
|
||||
rmutex->lock = 1;
|
||||
pthread_mutex_unlock(&(rmutex->mutex));
|
||||
|
||||
return 0; //Everything is A-OK
|
||||
}
|
||||
}
|
||||
|
||||
int rec_mutex_unlock(RecMutex *rmutex) {
|
||||
if (rmutex->owner == CurrentThread()) {
|
||||
rmutex->lock--;
|
||||
} else {
|
||||
return -2; //called without reason = error
|
||||
}
|
||||
|
||||
if (rmutex->lock == 0) {
|
||||
rmutex->owner = -1;
|
||||
pthread_cond_signal(&(rmutex->locked));
|
||||
} else if (rmutex->lock < 0) {
|
||||
return -1; //lock is broken = error
|
||||
}
|
||||
|
||||
return 0; //everything is A-OK
|
||||
}
|
||||
|
||||
int rec_mutex_init(RecMutex *rmutex) {
|
||||
pthread_mutex_init(&(rmutex->mutex), NULL);
|
||||
pthread_cond_init(&(rmutex->locked),NULL);
|
||||
rmutex->lock = 0;
|
||||
rmutex->owner = -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Question 2:
|
||||
-----------
|
||||
|
||||
a) No context switch is needed (everything done at user level). Very fast since only a stack and program counter need to be switched.
|
||||
b) The LWP has to be switched. This is relatively slow as it has to switch the process control block (with associated register data), accounting information, and memory information.
|
||||
c) Full Context switch is needed. Slowest of these 4 situations. The memory address space has to be switched to that of the other process in addition to all the other contents of the LWP's associated with that process.
|
||||
d) Faster than b and c (but slower than a) as it just requires switching between kernel threads. This basically means switching a small data structure and stack and is relatively fast.
|
||||
|
||||
Question 3:
|
||||
-----------
|
||||
|
||||
Possible. Requires change to unlock return values to avoid using C++ local variables. I just didn't figure out the macro on my own, so I can't write it here out of pride :(
|
||||
Reference in New Issue
Block a user