We are going to use 1 producer thread and 5 consume threads. They are going to r
ID: 3625772 • Letter: W
Question
We are going to use 1 producer thread and 5 consume threads. They are going to run
forever. There are two versions of the algorithm:
1. Without using semaphores (proj7v1.cpp)
2. With sempahores (proj7v2.cpp)
Submit both programs with sample outputs for both. Try to highlight the differences
between both outputs. Feel free to insert sleep() in appropriate places to enable strangebehavior. Try to keep those sleep() calls in both programs too.
Use the following diagrams and code to guide you through the project. We are going to usean array of 20 integers (that is, n = 20).
Solution: No semaphores
Producer
while (true) {
v = produce();
while ((in + 1) % n == out)
/* do nothing */;
append(v);
}
Consumer
while (true) {
while (in == out)
/* do nothing */;
w = take();
consume(w);
}
solution: With semaphores
Semaphore num = 0, c = 1, e = sizeofbuffer;
Producer
while (true) {
v = produce();
semWait(e);
append(v);
semPost(num);
}
Consumer
while (true) {
semWait(num);
semWait(c);
w = take();
semPost(c);
semPost(e);
consume(w);
}
append(v):
b[in] = v;
in= (in + 1) % n;
int take()
w = b[out];
sleep(1);
out = (out + 1) % n;
return w;
Array b[] can be an array of 20 integers. produce() can be as simple as return the next
integer in the sequence. consume(w) can simply print w out.
You may want to define & use a class for Buffer which has this array and append() and
take() as its methods.
Note: You need to specify lpthread library to compile your programs: g++ *.cpp –lpthread
Here is the sample output for v2:
Producer adds 1
Producer adds 2
Consumer5: 1
Consumer2: 2
Producer adds 3
Producer adds 4
Producer adds 5
Consumer3: 3
Consumer1: 4
Consumer4: 5
Producer adds 6
Consumer1: 6
Producer adds 7
Producer adds 8
Producer adds 9
Producer adds 10
Consumer2: 7
Consumer4: 9
Consumer3: 8
Consumer5: 10
Producer adds 11
…
Explanation / Answer
poima nemam
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.