Question

In: Computer Science

Can you add more comments explaining what this code does? i commented what I know so...

Can you add more comments explaining what this code does? i commented what I know so far

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>

sem_t mutex,writeblock;
int data = 0,rcount = 0;

int sleepLength = 2; // used to represent work

void *reader(void *arg)
{
int f;
f = ((int)arg);
sem_wait(&mutex); // decrement by 1 if
rcount = rcount + 1;
if(rcount==1)
sem_wait(&writeblock);
sem_post(&mutex);
printf("Data read by the reader%d is %d\n",f,data); //shows current reader and data
sleep(sleepLength); // 1 second of "work" is being done here
sem_wait(&mutex);
rcount = rcount - 1;
if(rcount==0)
sem_post(&writeblock);
sem_post(&mutex);
}

void *writer(void *arg)
{
int f;
f = ((int) arg);
sem_wait(&writeblock);
data++; //increases data by 1
printf("Data writen by the writer%d is %d\n",f,data); //shows current writer and data
sleep(sleepLength); // 1 second of "work" is being done here
sem_post(&writeblock);
}

int main()
{
int i,b;
pthread_t rtid[5],wtid[5];
sem_init(&mutex,0,1);
sem_init(&writeblock,0,1);
for(i=1;i<=5;i++)//loop to create writers and readers
{
pthread_create(&wtid[i],NULL,writer,(void *)i);
pthread_create(&rtid[i],NULL,reader,(void *)i);
//printf("looping in for\n");
}
for(i=1;i<=5;i++)//loop for
{
pthread_join(wtid[i],NULL);
pthread_join(rtid[i],NULL);
}
return 0;//resetting
}

Solutions

Expert Solution

This is standard reader writer problem.for reference , I am attaching below image.

===========================================================================


#include<stdio.h>

#include<pthread.h>

#include<semaphore.h>

#include<unistd.h>

sem_t mutex,writeblock; // These will be used to check if there is mutual exclusion between blocks

int data = 0,rcount = 0; //Data will be written by writer and rcount will store reader’s count

int sleepLength = 2; // used to represent work

void *reader(void *arg)

{

int f;

f = ((int)arg);

sem_wait(&mutex); // it will put wait condition on reader

rcount = rcount + 1; //increment reader count

if(rcount==1) //allows only one reader at time

sem_wait(&writeblock); //if reader is 1.meaning reader is writing then no one can write so it puts wait

sem_post(&mutex); //send signal to reader ..now ready to read

printf("Data read by the reader%d is %d\n",f,data); //shows current reader and data

sleep(sleepLength); // 1 second of "work" is being done here

sem_wait(&mutex);// it will put wait condition on reader

rcount = rcount - 1; //and it will reduce count and make it free

if(rcount==0) //Now no one is reading,then writer can write

sem_post(&writeblock); //signal writer for writing

sem_post(&mutex);// After all this,again reader can write,so it sends signal

}

void *writer(void *arg)

{

int f;

f = ((int) arg);

sem_wait(&writeblock); // It will stop all writer

data++; //increases data by 1 which will be written

printf("Data writen by the writer%d is %d\n",f,data); //shows current writer and data

sleep(sleepLength); // 1 second of "work" is being done here

sem_post(&writeblock);// It will send signal and makes value 1,so that other writers can write

}

int main()

{

int i,b;

pthread_t rtid[5],wtid[5]; // 5 threads are created

sem_init(&mutex,0,1);// 0 means it is shared across threads and 1 means it is initial value

sem_init(&writeblock,0,1); means it is shared across threads and 1 means it is initial value

for(i=1;i<=5;i++)//loop to create writers and readers

{

pthread_create(&wtid[i],NULL,writer,(void *)i);

pthread_create(&rtid[i],NULL,reader,(void *)i);

//printf("looping in for\n");

}

//All thread will be joined after execution

for(i=1;i<=5;i++)//loop for

{

pthread_join(wtid[i],NULL);

pthread_join(rtid[i],NULL);

}

return 0;//resetting

}


Related Solutions

Can someone please add clear and concise comments thoroughly explaining each line of code below. Just...
Can someone please add clear and concise comments thoroughly explaining each line of code below. Just need help understanding the code, don't need to modify it. The purpose of the code is to count the frequency of words in a text file, and return the most frequent word with its count. It uses two algorithms: Algorithm 1 is based on the data structure LinkedList. It maintains a list for word frequencies. The algorithm runs by scanning every token in the...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
I have this mystery code. I dont know what the code does. Can somone please explain...
I have this mystery code. I dont know what the code does. Can somone please explain with examples. (python 3.xx) from typing import Dict, TextIO, Tuple, List def exam(d1: Dict[str, List[int]], d2: Dict[int, int]) -> None: """ *Mystery code* """ for key in d1: value = d1[key] for i in range(len(value)): value[i] = d2[value[i]]   
Can someone please write clear and concise comments explaining what each line of code is doing...
Can someone please write clear and concise comments explaining what each line of code is doing for this program in C. I just need help tracing the program and understand what its doing. Thanks #include <stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> int join(char *com1[], char *com2[]) {    int p[2], status;    switch (fork()) {        case -1:            perror("1st fork call in join");            exit(3);        case 0:            break;        default:...
Basically, the code already functions properly. Could you just write in method header comments explaining what...
Basically, the code already functions properly. Could you just write in method header comments explaining what the method does and what the parameters are? Some of them are already done. Additionally could you change the variables and method names to make them more descriptive of what they're actually holding? Thank you! import java.util.Scanner; /** * This class contains the entire program to print out a yearly calendar. * * @author * @author TODO add your name here when you contribute...
hi,I have this C++ program,can someone add few comments with explanation what is the logic and...
hi,I have this C++ program,can someone add few comments with explanation what is the logic and what is what?thank you I m total beginner #include <iostream> using namespace std; int ArraySum(int MyArray[], int size){ int* p = MyArray; int sum = 0; while(p<MyArray+size){ sum += *p; p++; } return sum; } int main() { int MyArray[10] = {4, 0, 453, 1029, 44, 67, 111, 887, 4003, 1002}; cout<<ArraySum(MyArray,10); return 0; }
This is a python program. Put comments explaining the code, please. Suppose you have been tasked...
This is a python program. Put comments explaining the code, please. Suppose you have been tasked with writing a Python program (using linked lists) to keep track of computer equipment. For each piece of equipment, we track its name, purchase date, purchase amount, and quantity on hand. Write a program that completes the following tasks: allow the user to add a piece of equipment to the front of the list; allow the user to update the quantity of a piece...
please I don't understand this code. Can you put comments to explain the statements. Also, if...
please I don't understand this code. Can you put comments to explain the statements. Also, if there any way to rewrite this code to make it easier, that gonna help me a lot. import java.io.*; import java.util.*; public class State {    private int citi1x,citi1y; private int pop1; private int citi2x,citi2y; private int pop2; private int citi3x,citi3y; private int pop3; private int citi4x,citi4y; private int pop4; private int plantx,planty; public int getCity1X(){ return citi1x; } public int getCity1Y(){ return citi1y;...
Source code with comments explaining your code in C# Program 2: Buh-RING IT! For this assignment,...
Source code with comments explaining your code in C# Program 2: Buh-RING IT! For this assignment, you’re going to simulate a text-based Role-Playing Game (RPG). Design (pseudocode) and implement (source) for a program that reads in 1) the hero’s Hit Points (HP – or health), 2) the maximum damage the hero does per attack, 3) the monster’s HP and 4) the maximum monster’s damage per attack. When the player attacks, it will pick a random number between 0 and the...
HOW DO I ADD ON TO THIS CODE SO THAT IT DISPLAYS ALL THE VALUES INPUT...
HOW DO I ADD ON TO THIS CODE SO THAT IT DISPLAYS ALL THE VALUES INPUT BY THE USER AS SPECIFIED IN THEH FIRST PART OF THE QUESTION? Ask the user to enter a number and display the number, followed by ***, followed by the number squared, followed by &&&, and followed by the number cubed. Allow the user to enter as many numbers as he/she wishes. So, use a reasonable sentinel value to end the loop (for example, -999)....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT