hello.
I'm trying to solve a problem in C, with an efficient system of locks(mutex). Is a simulation of writer/reader program.
The program have three restrictions:
- there are multiple readers who can simultaneously read what the writers have written;
- simultaneous writes by different writers are not allowed;
- simultaneous writing and readind is not allowed;
This is a example what the program should print:
W0: Start
W0: End
W1: Start
W1: End
R0: Start
R1: Start
R0: End
R2: Start
R1: End
R2: End
W2: Start
W2: End
I've walked around with it and can't figured out how to solve the third restriction.
I have some clues:
You will need at least two locks. You should count the number of threads that are simultaneously reading and allow only the first thread of the batch to lock out the writers and the last one to finish the read to unlock them.
I already do this code, but is not working in the correct manner:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define N 3
/*Declaration*/
void *writer(int n);
void *reader(int n);
void clean();
/*Init*/
pthread_mutex_t mutex,mutex1;
int main(int argc, char **argv)
{
int i;
pthread_t thrR[N];
pthread_t thrW[N];
pthread_mutex_init(&mutex,NULL);
pthread_mutex_init(&mutex1,NULL);
for(i=0;i<N;i++){
pthread_create(&thrW[i],NULL,writer, (void *)i);
pthread_create(&thrR[i],NULL,reader, (void *)i);
}
for(i=0;i<N;++i){
pthread_join(thrW[i], NULL);
pthread_join(thrR[i], NULL);
}
/*Clean Resources*/
clean();
return 0;
}
void *writer(int n){
int i;
for(i=0;i<5;++i){
pthread_mutex_lock(&mutex);
printf("W%d:S \n",n);
sleep(2*n);
printf("W%d:E \n",n);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *reader(int n){
int i=0;
if (n==0) pthread_mutex_unlock(&mutex);
while(i<5){
printf("R%d:S \n",n);
pthread_mutex_lock(&mutex1);
sleep(n);
pthread_mutex_unlock(&mutex1);
printf("R%d:E \n",n);
i++;
}
if (n==N) pthread_mutex_lock(&mutex);
return NULL;
}
void clean()
{
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex1);
}
I hope someone can help me.