CS计算机代考程序代写 Java My sites / 21S-COMSCI111-1 / Site info / Final Exam Spring 2021 – Finals week

My sites / 21S-COMSCI111-1 / Site info / Final Exam Spring 2021 – Finals week

Spring 2021 – COM SCI111-1 – EYOLFSON

Question 15
Not yet answered

Points out of 15.00

Locking (40 minutes).

You’re tasked with implementing a bank account transfer that works with multiple threads. You create a bank account structure with a
lock and an amount representing the dollar amount of the bank account. This bank makes no cents (get it?) and only tracks whole dollar
amounts. You remember how Java implements monitors and write transfer to lock the entire function. Your initial implementation is as
follows:

struct bank_account {
pthread_mutex_t lock;
int amount;
};

void transfer(struct bank_account *this,
int amount,
struct bank_account *that) {
pthread_mutex_lock(&this->lock);
if (this->amount >= amount) {
this->amount -= amount;
that->amount += amount;
}
pthread_mutex_unlock(&this->lock);
}

Give an example of a data race that could occur. You may explain it using abstract bank accounts such as: bank account A, B, and C.

                     

 

https://ccle.ucla.edu/my/
https://ccle.ucla.edu/course/view.php?id=101241
https://ccle.ucla.edu/course/view.php?id=101241&section=0
https://ccle.ucla.edu/mod/quiz/view.php?id=3983573

Question 16
Not yet answered

Points out of 15.00

You change the code to the following:

void transfer(struct bank_account *this,
int amount,
struct bank_account *that) {
pthread_mutex_lock(&this->lock);
pthread_mutex_lock(&that->lock);
if (this->amount >= amount) {
this->amount -= amount;
that->amount += amount;
}
pthread_mutex_unlock(&that->lock);
pthread_mutex_unlock(&this->lock);
}

Your code now does not have any data races, but can deadlock. What are two things you could do to prevent the deadlock? You do not
have to write any code. Explain what you would do to implement each strategy (in different paragraphs please).

                     

 

Question 17
Not yet answered

Points out of 10.00

Someone suggests using two variables is wasteful, you can just use a semaphore that keeps track of the amount of money in each
account.They provide the following implementation that has no data races:

struct bank_account {
sem_t amount;
};

void transfer(struct bank_account *this,
int amount,
struct bank_account *that) {
for (int i = 0; i < amount; ++i) { sem_wait(&this->amount);
sem_post(&that->amount);
}
}

Explain how you could STILL effectively deadlock a process running 2 threads using this code. Please provide an example.

                    

More 

 

◀ Midterm

Jump to…

Lab 1B Week 1 ▶

https://ccle.ucla.edu/mod/quiz/view.php?id=3875405&forceview=1
https://ccle.ucla.edu/mod/kalvidres/view.php?id=3834460&forceview=1