Skip to content

Instantly share code, notes, and snippets.

@junfenglx
Created November 14, 2013 10:53
Show Gist options
  • Save junfenglx/7464889 to your computer and use it in GitHub Desktop.
Save junfenglx/7464889 to your computer and use it in GitHub Desktop.
readers and writers.readers_preference
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
int count = 0;
int share=0;
pthread_t maintid;
sem_t roomEmpty;
sem_t mutex;
void* reader(void *arg)
{
pthread_join(maintid,NULL);
int tid;
tid=*(int*)arg;
sem_wait(&mutex);
count++;
if (count==1)
sem_wait(&roomEmpty);
printf("count: %d.\n",count);
sem_post(&mutex);
printf("reader %d in critical position.\nreads %d\n",tid,share);
sem_wait(&mutex);
count--;
if (count==0){
printf("readers all left.\n");
sem_post(&roomEmpty);
}
sem_post(&mutex);
printf("reader %d left critical position.\n",tid);
pthread_exit((void*)0);
}
void* writer(void *arg)
{
pthread_join(maintid,NULL);
int tid;
tid=*(int*)arg;
sem_wait(&roomEmpty);
share++;
printf("writer %d in.\nwrites %d\n",tid,share);
sem_post(&roomEmpty);
printf("writer %d left critical position.\n",tid);
pthread_exit((void*)0);
}
int main(int argc,char *argv)
{
int nr=0,nw=0;
int i;
int *idreaders,*idwriters;
pthread_t *readers;
pthread_t *writers;
sem_init(&roomEmpty,0,1);
sem_init(&mutex,0,1);
maintid=pthread_self();
printf("How many readers do you want?\n");
scanf("%d",&nr);
printf("How many writers do you want?\n");
scanf("%d",&nw);
readers=(pthread_t*)malloc(nr*sizeof(pthread_t));
writers=(pthread_t*)malloc(nw*sizeof(pthread_t));
idreaders=(int*)malloc(nr*sizeof(int));
idwriters=(int*)malloc(nw*sizeof(int));
for (i=0;i<nr;++i){
idwriters[i]=i+1;
pthread_create(readers+i,NULL,reader,idwriters+i);
}
for (i=0;i<nw;++i){
idreaders[i]=i+1;
pthread_create(writers+i,NULL,writer,idreaders+i);
}
for (i=0;i<nr;++i)
pthread_detach(*(readers+i));
for (i=0;i<nw;++i)
pthread_detach(*(writers+i));
/*sem_destroy(&mutex);
sem_destroy(&roomEmpty);
free(readers);
free(writers);
return 0;*/
pthread_exit((void*)0);//now readers and writers all awake.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment