Question

You are given a sample code that when edited/ improved/completed -will work as a producer consumer...

You are given a sample code that when edited/ improved/completed -will work as a producer consumer synchronized solution.
In addition to the counter, you will implement a circular linked list as a buffer of size 200 that stores data items 0 or 1. The producer and consumer take *random* turns to produce and consume- *random* numbers of elements ( turning 1 to a 0 and visa-versa-each time, as discussed in class). After each turn of the producer and/or consumer, your code will printout
the contents of the linked list ( sequence of 0s and 1s)
the number of elements produced/ or consumed
the total of numbers of elements in the buffer

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

using namespace std;
mutex g_lock;
mutex g_lock1;
int counter = 0;
void func()
{
   g_lock1.lock();
   for (int i = 1; i < 5; i++)// make this a random number instead of 5
   {
  
   cout << "entered procucer " << std::this_thread::get_id() << endl;
   this_thread::sleep_for(std::chrono::seconds(rand() % 10));
   counter++;
   cout << " counter in process " << this_thread::get_id() << " producer; counter = : " << counter << endl;
   }
   //cout << " counter in process " << this_thread::get_id() << " :" << counter << endl;
   cout << "***********" << endl;
   cout << "leaving thread " << std::this_thread::get_id() << std::endl;
   g_lock1.unlock();

}
void func1()
{
   g_lock.lock();

   cout << "consumer active " << std::this_thread::get_id() << endl;
   for (int i = 1; i < 5; i++)
   {
       this_thread::sleep_for(std::chrono::seconds(rand() % 10));
       counter--;
       cout << " counter in process " << this_thread::get_id() << " :" << counter << endl;
   }
   cout << " counter in process " << this_thread::get_id() << " consumer; counter = :" << counter << endl;
   cout << "***********" << endl;
   cout << "leaving thread " << std::this_thread::get_id() << std::endl;
   g_lock.unlock();

}

int main()
{
   srand((unsigned int)time(0));

   thread t1(func);
   thread t2(func1);

   t1.join();
   t2.join();

   return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

if you take n instead of 5 in the for loop then the producer program will run for n times. As before entering into the the critical section producer locked the resource which means turned the value of lock1 from 0 to 1. This process have to done first as counter is 0 so no process in critical section. It will print 1.

now if preemption happens then consumer will also turn lock 0 to 1. After entering it will print 0 as counter value now changed by consumer to 0.

In this way both of them will run for n times and each time they will print value(we assumed that preemption happens right after change of values of counter.)

(assume lock=0, lock1=0 initially)

So total n+n= 2n elements will be printed.

There is no t clearly stated what values will be stored in the buffer. But we assume general case where each change of values will be stored. Now the sequence of values can be anything which mainly depends on the preemption sequence. We assume that preemption happens only after the change of values of counter then first value will be stored as 1. Because counter initial value was 0 and only producer can change the value to 1(binary semaphore/mutex can only have 0 or 1 ). If consumer would have changed then value would have been -1. So first value stored is 1 now consumer turns value to 0 and this 0 will be stored. Again producer will change.

In this way values will be laternatively changed to 0 to 1 then 1 to 0.

So the elements will be 101010101010101010....total 200 1's and 0's(100 1's and 100 0's). Because buffer size is 200.

Add a comment
Know the answer?
Add Answer to:
You are given a sample code that when edited/ improved/completed -will work as a producer consumer...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a c++ code into the given code  to find composite numbers from the given random number...

    Write a c++ code into the given code  to find composite numbers from the given random number list. The composite numbers is only counted once if there is a repeated number. I need to use this code and add on a code to find if the numbers generated is a composite function. Please help #include <cmath> #include <cstdlib> #include <ctime> #include <iostream> #include <vector> using namespace std; int main() {    srand(time(NULL)); int size_of_list = 0; // the number of random...

  • Lab 10A Measure the program execution time One easy way to measure the program execution time is ...

    Lab 10A Measure the program execution time One easy way to measure the program execution time is encapsulate the useful timing functionality of C++ chrono library, This is illustrated inhttps://www.learncpp.com/cpp-tutorial/8-16-timing-your-code/ The example usingChronoTimer.cpp (Github/m10) is an example program using this chrono Timer class object to measure the Sorting on on an integer array of 10000 random integers based on the Bubble Sort vs. the C++ built-in Sort (an https://www.quora.com/Which-sorting-algorithm-does-STL-standard-template-library-use-in-c++. ) Please measure the performance of sorting the same array used...

  • Producer and Consumer Code in C++ The program will contain two methods- one each for the...

    Producer and Consumer Code in C++ The program will contain two methods- one each for the producer and consumer. Both methods share access to an integer array buffer of size 50 with all values initialized to 0 at the beginning and an integer variable counter initialized to 0. As given below, the producer accesses the buffer elements and updates the element to 1 ( indicating production). The consumer changes a buffer elements to 0 (indicating consumption). Enhancements and modifications: You...

  • operating system engineering , please read the question and solve on the given skeleton code ....

    operating system engineering , please read the question and solve on the given skeleton code . Write a multi-threaded program with Semaphores as counters and pthread_mutex_t mutex to solve the producer-consumer problem: A bounded buffer is simply a global integer array of size N (2) which can be accessed by multiple threads. • Create two types of threads - Producer (2) and Consumer (2). Producers will write to the buffer, and the consumers will read the buffer. In this scenario,...

  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • C++ Linux Question : Remove Nth Node from end of list Given a linked list, remove...

    C++ Linux Question : Remove Nth Node from end of list Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. (i.e. n is greater than 0) Follow up: Could you do this in one pass? Hint: Maintain two pointers and update one with...

  • The provided code is my solution, stripped of the details needed to make it work. It...

    The provided code is my solution, stripped of the details needed to make it work. It is not a “good” program. It lives in a single file, does not use classes, and it has those evil global variables. That is by design. I want to to craft code. Use my code as a guide to help you put together the needed parts. #include #include #include // defaults const int MAX_STEPS = 100; // how long do we run the simulation...

  • I can't get my code to work on xcode and give me an output. #include <conio.h> #include <cstdlib> #incl...

    I can't get my code to work on xcode and give me an output. #include <conio.h> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> using namespace std; // So "std::cout" may be abbreviated to "cout" //Declare global arrays int dummy1[10]; int dummy2[10]; int dummy3[10]; int universalSet[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Function to return statement "Empty thread" when the resultant set is empty string isEmpty(int arr[]) { string...

  • How can I write this code (posted below) using vectors instead of arrays? This is the...

    How can I write this code (posted below) using vectors instead of arrays? This is the task I have and the code below is for Task 1.3: Generate twenty random permutations of the number 0, 1, 2, ..., 9 using of the algorithms you designed for Task 1.3. Store these permutations into a vector and print them to the screen with the additional information of unchanged positions and number of calls torand(). Calculate the total numbers of unchanged positions. Compare...

  • Can you tell me what is wrong and fix this code. Thanks #include <iostream> #include <string>...

    Can you tell me what is wrong and fix this code. Thanks #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; //function void displaymenu1(); int main ( int argc, char** argv ) { string filename; string character; string enter; int menu1=4; char repeat; // = 'Y' / 'N'; string fname; string fName; string lname; string Lname; string number; string Number; string ch; string Displayall; string line; string search; string found;    string document[1000][6];    ifstream infile; char s[1000];...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT