Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #define N 5
- int readcount, writecount;
- int reader_num[N] = {0,1,2,3,4};
- pthread_mutex_t the_mutex, db, read, readcnt, writecnt;
- void read_db(int i)
- {
- //pthread_mutex_lock(
- printf("reader %d reading DB\n", i);
- usleep(10000);
- }
- void write_data()
- {
- printf("writer writing to the DB\n");
- usleep(10000);
- }
- void * reader(void * num)
- {
- int i = (int)num;
- while (1)
- {
- pthread_mutex_lock(&the_mutex);
- pthread_mutex_lock(&read);
- pthread_mutex_lock(&readcnt);
- readcount++;
- if ( readcount == 1 )
- pthread_mutex_lock(&db);
- pthread_mutex_unlock(&readcnt);
- pthread_mutex_unlock(&read);
- pthread_mutex_unlock(&the_mutex);
- read_db(i);
- pthread_mutex_lock(&the_mutex);
- pthread_mutex_lock(&readcnt);
- readcount--;
- if ( readcount == 0 )
- pthread_mutex_unlock(&db);
- pthread_mutex_lock(&readcnt);
- pthread_mutex_unlock(&the_mutex);
- }// end while
- }// end reader
- void * writer()
- {
- while (1)
- {
- pthread_mutex_lock(&db);
- pthread_mutex_lock(&writecnt);
- writecount++;
- if ( writecount == 1 )
- pthread_mutex_lock(&read);
- pthread_mutex_unlock(&writecnt);
- write_data();
- pthread_mutex_lock(&writecnt);
- writecount--;
- if ( writecount == 0 )
- pthread_mutex_unlock(&read);
- pthread_mutex_unlock(&writecnt);
- pthread_mutex_unlock(&db);
- }//end while
- }//end writer
- int main()
- {
- int i;
- readcount = 0; writecount = 0;
- pthread_mutex_init(&the_mutex, 0);
- pthread_mutex_init(&db, 0);
- pthread_mutex_init(&read, 0);
- pthread_mutex_init(&readcnt, 0);
- pthread_mutex_init(&writecnt, 0);
- pthread_t writer_id, reader_id[N];
- pthread_create(&writer_id, 0, writer, 0);
- for ( i = 0; i < N; i++ )
- pthread_create(&reader_id[i], 0, reader, (void *)reader_num[i]);
- pthread_join(writer_id, NULL);
- for ( i = 0; i < N; i++ )
- pthread_join(reader_id[i], NULL);
- pthread_mutex_destroy(&the_mutex);
- pthread_mutex_destroy(&db);
- pthread_mutex_destroy(&read);
- pthread_mutex_destroy(&readcnt);
- pthread_mutex_destroy(&writecnt);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement