How reader and writer problem was implemented and come up
with effective solution for reader and writer problem in
case we have n readers and 1 writer.

Answers were Sorted based on User's Feedback



How reader and writer problem was implemented and come up with effective solution for reader and wr..

Answer / sriram

The reader and writer problem is IMPLEMENTED THROUGH
SEMAPHORES.

THE EFFECTIVE SOLUTION TO SOLVE THE READER AND WRITER
SOLUTION IS :


A) If a writer is waiting in the ready queue to enter
into the critical section, then the current reading process
should be completed without delay.

B) Only one reader can be put into the ready queue
because the writer is waiting.

c) The semaphores such as ReadCount-to count the number
of reader in ready queue,
Reader and Writer, these are the important semaphores to
solve the reader and writer problem.

Is This Answer Correct ?    23 Yes 4 No

How reader and writer problem was implemented and come up with effective solution for reader and wr..

Answer / avinash

#include<pthread.h>
#include<semaphore.h>
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
sem_t mutex, cnt;

int readcount = 0;
int rcnt, wcnt;

void *wfun (void *args)
{
sem_wait (&cnt);
printf("\nIn writer : value of read cnt is %d", readcount );
sem_post(&cnt);
}

void *rfun (void *args)
{
sem_wait(&mutex);
readcount ++;
if(readcount == 1)
sem_wait(&cnt);
sem_post(&mutex);
printf("\nIn reader : reader has incremented read cnt, its value is %d",readcount );
sem_wait(&mutex);
readcount --;
if(readcount == 0)
sem_post(&cnt);
sem_post(&mutex);

}

int main()
{

int i, *t;
t = (int*)malloc(sizeof(int));

printf("\nenter number of readers: ");
scanf("%d",&rcnt);
printf("\nenter number of writers: ");
scanf("%d",&wcnt);

//initialize semaphores
sem_init(&mutex,0,1);
sem_init(&cnt,0,1);
pthread_t rdrs[10];
pthread_t wrs[10];

//create reader threads
for(i=0;i<rcnt;i++)
{
*t = i;
pthread_create(&rdrs[i],NULL,rfun, (void *)t);
}

//create writer threads
for(i=0;i<wcnt;i++)
{
*t=i;
pthread_create(&wrs[i],NULL,wfun,(void *)t);
}

for(i=0;i<rcnt;i++)
pthread_join(rdrs[i],NULL);

for(i=0;i<wcnt;i++)
pthread_join(wrs[i],NULL);
return(0);
}

Is This Answer Correct ?    6 Yes 1 No

How reader and writer problem was implemented and come up with effective solution for reader and wr..

Answer / masud

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

#define MAXTHREAD 10 /* define # readers */


void access_database(); /* prototypes */
void non_access_database();

void* reader(void*);
void* writer(void*);

sem_t q; /* establish que */
int rc = 0; /* number of processes reading or
wanting to */
int wc = 0;
int write_request = 0;

int main()
{
pthread_t readers[MAXTHREAD],writerTh;
int index;
int ids[MAXTHREAD]; /* readers and initialize mutex, q
and db-set them to 1 */
sem_init (&q,0,1);
for(index = 0; index < MAXTHREAD; index ++)
{
ids[index]=index+1;
/* create readers and error
check */
if(pthread_create(&readers[index],0,reader,&ids
[index])!=0){
perror("Cannot create reader!");
exit(1);

}
}
if(pthread_create(&writerTh,0,writer,0)!=0){
perror("Cannot create writer"); /* create
writers and error check */
exit(1);
}

pthread_join(writerTh,0);
sem_destroy (&q);
return 0;
}

void* reader(void*arg) /* readers function
to read */
{
int index = *(int*)arg;
int can_read;
while(1){
can_read = 1;

sem_wait(&q);
if(wc == 0 && write_request == 0) rc++;
else can_read = 0;
sem_post(&q);

if(can_read) {
access_database();
printf("Thread %d reading\n", index);
sleep(index);

sem_wait(&q);
rc--;
sem_post(&q);
}

sched_yield();
}
return 0;
}

void* writer(void*arg) /* writer's function to
write */
{
int can_write;
while(1){
can_write = 1;
non_access_database();

sem_wait (&q);
if(rc == 0) wc++;
else { can_write = 0; write_request = 1; }
sem_post(&q);

if(can_write) {
access_database();
printf("Writer is now writing...Number of
readers: %d\n",rc);

sleep(3);

sem_wait(&q);
wc--;
write_request = 0;
sem_post(&q);
}

sched_yield();
}
return 0;
}

void access_database()
{

}


void non_access_database()
{

}

Is This Answer Correct ?    7 Yes 3 No

How reader and writer problem was implemented and come up with effective solution for reader and wr..

Answer / ashwini

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

pthread_mutex_t m;

void* writer(void*);
void* reader(void*);

FILE *fp;



main()
{
pthread_t tid1,tid2,tid3;
pthread_mutex_init(&m,NULL);
pthread_create(&tid2,NULL,reader,NULL);
pthread_create(&tid1,NULL,writer,NULL);
pthread_create(&tid3,NULL,reader,NULL);

pthread_join(tid2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid3,NULL);
}
void* writer(void *str)
{
pthread_mutex_lock(&m);

fp=fopen("file1.txt","w");
global += 35;
fprintf(fp,"%d",100);
fclose(fp);
pthread_mutex_unlock(&m);
}
void* reader(void *param)
{
int abc;
pthread_mutex_lock(&m);
fp=fopen("file1.txt","r");
fscanf(fp,"%d",&abc);
printf("%d",global);
fclose(fp);
pthread_mutex_unlock(&m);
}

Is This Answer Correct ?    15 Yes 12 No

How reader and writer problem was implemented and come up with effective solution for reader and wr..

Answer / raj kumar

Readers: read data, never modify it
Writers: read data and modify it
criteria:
– Each read or write of the shared data must happen within
a critical section.
– Guarantee mutual exclusion for writers.
– Allow multiple readers to execute in the critical section
at once.
In this example, semaphores are used to prevent any writing
processes from changing information in the database while
other processes are reading from the database.
semaphore mutex = 1; // Controls access to
the reader count
semaphore db = 1; // Controls access to
the database
int reader_count; // The number of
reading processes accessing the data

Reader()
{
while (TRUE) { // loop forever
down(&mutex); // gain access
to reader_count
reader_count = reader_count + 1; // increment the
reader_count
if (reader_count == 1)
down(&db); // if this is
the first process to read the database,
// a down on db
is executed to prevent access to the
// database by a
writing process
up(&mutex); // allow other
processes to access reader_count
read_db(); // read the database
down(&mutex); // gain access
to reader_count
reader_count = reader_count - 1; // decrement
reader_count
if (reader_count == 0)
up(&db); // if there are
no more processes reading from the
// database,
allow writing process to access the data
up(&mutex); // allow other
processes to access reader_countuse_data();
// use the data
read from the database (non-critical)
}

Writer()
{
while (TRUE) { // loop forever
create_data(); // create data
to enter into database (non-critical)
down(&db); // gain access
to the database
write_db(); // write
information to the database
up(&db); // release
exclusive access to the database
}

Is This Answer Correct ?    3 Yes 3 No

How reader and writer problem was implemented and come up with effective solution for reader and wr..

Answer / kiran baviskar

#include<pthread.h>
//#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>

pthread_mutex_t x,wsem;
pthread_t tid;
int readcount;

void intialize()
{
pthread_mutex_init(&x,NULL);
pthread_mutex_init(&wsem,NULL);
readcount=0;
}

void * reader (void * param)
{
int waittime;
waittime = rand() % 5;
printf("
Reader is trying to enter");
pthread_mutex_lock(&x);
readcount++;
if(readcount==1)
pthread_mutex_lock(&wsem);
printf("
%d Reader is inside ",readcount);
pthread_mutex_unlock(&x);
sleep(waittime);
pthread_mutex_lock(&x);
readcount--;
if(readcount==0)
pthread_mutex_unlock(&wsem);
pthread_mutex_unlock(&x);
printf("
Reader is Leaving");
}

void * writer (void * param)
{
int waittime;
waittime=rand() % 3;
printf("
Writer is trying to enter");
pthread_mutex_lock(&wsem);
printf("
Write has entered");
sleep(waittime);
pthread_mutex_unlock(&wsem);
printf("
Writer is leaving");
sleep(30);
exit(0);
}

int main()
{
int n1,n2,i;
printf("
Enter the no of readers: ");
scanf("%d",&n1);
printf("
Enter the no of writers: ");
scanf("%d",&n2);
for(i=0;i<n1;i++)
pthread_create(&tid,NULL,reader,NULL);
for(i=0;i<n2;i++)
pthread_create(&tid,NULL,writer,NULL);
sleep(30);
exit(0);
}

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More C++ Code Interview Questions

We need to write the function to check the password entered is correct or not based on the following conditions.. a) It must have atleast one lower case character and one digit. b)It must not have any Upper case characters and any special characters c) length should be b/w 5-12. d) It should not have any same immediate patterns like abcanan1 : not acceptable coz of an an pattern abc11se: not acceptable, coz of pattern 11 123sd123 : acceptable, as not immediate pattern adfasdsdf : not acceptable, as no digits Aasdfasd12: not acceptable, as have uppercase character

0 Answers  


Deriving time complexity of Binary tree and AVL tree, step by step.

4 Answers   NetApp,


What output does the following code generate? Why? What output does it generate if you make A::Foo() a pure virtual function? class A { A() { this->Foo(); } virtual void Foo() { cout << "A::Foo()" << endl; } }; class B : public A { B() { this->Foo(); } virtual void Foo() { cout << "A::Foo()" << endl; } }; int main(int, char**) { A objectA; B objectB; return 0; }

0 Answers  


1. Write a program that performs the following. The user inputs a number and then enters a series of numbers from 1 to that number. Your program should determine which number (or numbers) is missing or duplicated in the series, if any. For example, if the user entered 5 as the initial number and then entered the following sequences, the results should be as shown. Input Sequence Output ---------------------- --------------- 1 2 3 4 5 Nothing bad However, if 7 were the high number, the user would see the results on the right for the following number entries: Input Sequence Output ---------------------- --------------- 1 3 2 4 5 Missing 6 Missing 7 And if 10 were the high number and the user entered the numbers shown on the left, note the list of missing and duplicate numbers: Input Sequence Output ---------------------- --------------- 1 2 4 7 4 4 5 10 8 2 6 Duplicate 2 ( 2 times) Missing 3 Duplicate 4 ( 3 times ) Missing 9

1 Answers  


using friend function find the maximum number from given two numbers from two different classes.write all necessary functions and constructor for the classes.

1 Answers   TCS,






write a program that prompt the user to enter his height and weight,then calculate the body mass index and show the algorithm used

0 Answers   Jomo Kenyatta University,


Write code for the multiplication of COMPLEX numbers?

0 Answers   IBM,


Given a table of the form: Product Sold on A 1/1/1980 B 1/1/1980 C 1/1/1980 A 1/1/1980 B 1/1/1980 C 2/1/1980 A 2/1/1980 There are 30 products and 10,000 records of such type. Also the month period during which sales happened is given to u. Write the program to display the result as: Product Month No. of copies A January 12 A February 15 A March 27 B January 54 B February 15 B March 10 C January 37

0 Answers  


Definition of priority queue was given. We have to implement the priority queue using array of pointers with the priorities given in the range 1..n. The array could be accessed using the variable top. The list corresponding to the array elements contains the items having the priority as the array index. Adding an item would require changing the value of top if it has higher priority than top. Extracting an item would require deleting the first element from the corresponding queue. The following class was given: class PriorityQueue { int *Data[100]; int top; public: void put(int item, int priority); // inserts the item with the given priority. int get(int priority); // extract the element with the given priority. int count(); // returns the total elements in the priority queue. int isEmpty(); // check whether the priority queue is empty or not. }; We had to implement all these class functions.

0 Answers   Nagarro, Wollega University,


output for printf("printf");

0 Answers  


Question 1: Implement a base class Appointment and derived classes Onetime, Daily, Weekly, and Monthly. An appointment has a description (for example, “see the dentist”) and a date and time. Write a virtual function occurs_on(int year, int month, int day) that checks whether the appointment occurs on that date. For example, for a monthly appointment, you must check whether the day of the month matches. Then fill a vector of Appointment* with a mixture of appointments. Have the user enter a date and print out all appointments that happen on that date. *This Should Be Done IN C++

0 Answers  


Given 1 to n random number, find top 10 maximum numbers and explain the time complexity of the algorithm.

1 Answers   IMO, NetApp,


Categories