Threads and locks problem Consider the code written by Harry Q. Bovik for the fo
ID: 3823774 • Letter: T
Question
Threads and locks problem
Consider the code written by Harry Q. Bovik for the following problem. Please assume that all necessary header files are included in the code and all system calls and accessory functions always succeed. You may assume that the locks have been initialized correctly in main(), which we do not show. Bovik comes to you and complains that funel () seems to misbehave. Is he lying or is there something wrong with his code? Defend your answer in 1-3 sentences. 2. Bovik is complaining about func2 () as well. He insists to your boss that this program sometimes hangs and your boss would like your opinion. Is Bovik lying again or is there a problem? Defend your answer in 1-3 sentences. pthread_mutex_r , count_1, .l_count; int ref_count, tid_1, tid_2, tid_3, tid_4; void .threadl(void .vargp) { tid_2 = pthroad_self(); pthread_mutex_lock (count_1); ref_count++; pthread_mutex_unlock (count_l); return(0); } void .thread2(void .vargp) ( tid_1 = pthread_self(); pthread_mutex_lock (count_l); pthread_kill(pthread_self (), SIGKILL); ref_count++; pthread_mutex_unlock (count_l); return(0); } void .thread3(void .vargp) (tid_3 = pthread_self(); pthread_mutex_lock (count_l); pthread_mutex_lock (l_count); ref_count++; pthread_mutex_unlock (l_count); pthread_mutex_unlock (count_l); return(0); void .thread4(void .vargp) tid_4 = pthread_self(); pthread_mutex_lock (l_count); pthread_mutex_lock (count_l); ref_count --; pthread_mutex_unlock (l_count); pthroad_mutex_unlock (count_l); return(0); }Explanation / Answer
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockDemo {
public static void main(String args[]) {
// Let's create a counter and shared it between three threads
// Since Counter needs a lock to protect its getCount() method
// we are giving it a ReentrantLock.
final Counter myCounter = new Counter(new ReentrantLock());
// Task to be executed by each thread
Runnable r = new Runnable() {
@Override
public void run() {
System.out.printf("Count at thread %s is %d %n",
Thread.currentThread().getName(), myCounter.getCount());
}
};
// Creating three threads
Thread t1 = new Thread(r, "T1");
Thread t2 = new Thread(r, "T2");
Thread t3 = new Thread(r, "T3");
//starting all threads
t1.start();
t2.start();
t3.start();
}
}
class Counter {
private Lock lock; // Lock to protect our counter
private int count; // Integer to hold count
public Counter(Lock myLock) {
this.lock = myLock;
}
public final int getCount() {
lock.lock();
try {
count++;
return count;
} finally {
lock.unlock();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.