Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Pristup bazi podataka obavlja se radi upisa i čitanja od strane više procesa.
- U jednom trenutku može*/
- /*postojati više procesa koji čitaju sadržaj iz baze podataka procedurom read_database(), ali ako jedan*/
- /*proces upisuje sadržaj u bazu podataka procedurom write_database(), nijednom drugom procesu nije*/
- /*dozvoljen pristup bazi podataka radi upisa i čitanja.
- Prednost imaju procesi koji čitaju sadržaj, tako da*/
- /*dok god ima procesa koji čitaju iz baze podataka, proces koji treba da upisuje podatke mora da čeka.*/
- /*Korišćenjem programskog jezika C napisati Linux program koji korišćenjem procesa i poznatih IPC*/
- /*mehanizama simulira prethodno opisani algoritam. (Sinhronizacion problem Čitaoci – pisci).*/
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- #include <string.h>
- #include <semaphore.h>
- #define N 20
- char baza[N][2];
- pthread_mutex_t mutex;
- pthread_cond_t notEmpty;
- pthread_cond_t notFull;
- int freeSpace = N;
- int head = 0;
- int tail = 0;
- void* readDatabase(void* a)
- {
- while(1)
- {
- pthread_mutex_lock(&mutex);
- while(freeSpace == N)
- pthread_cond_wait(¬Empty,&mutex);
- char t;
- t = baza[tail][0];
- tail = (tail+1) % N;
- printf("procitano %c sa poz %d\n",t,tail);
- fflush(stdout);
- freeSpace++;
- pthread_cond_signal(¬Full);
- pthread_mutex_unlock(&mutex);
- sleep(1);
- }
- }
- void* writeDatabase(void* a)
- {
- while(1)
- {
- pthread_mutex_lock(&mutex);
- while(freeSpace <= 0)
- pthread_cond_wait(¬Full,&mutex);
- head = (head+1)%N;
- baza[head][0] = 'r';
- baza[head][1] = '\0';
- printf("Upisano u bazu %c na poz %d\n",'r',head);
- fflush(stdout);
- freeSpace--;
- pthread_cond_signal(¬Empty);
- pthread_mutex_unlock(&mutex);
- sleep(1);
- }
- }
- int main(int argc,char* argv[])
- {
- pthread_t nit1;
- pthread_t nit2;
- pthread_t nit3;
- pthread_t nit4;
- pthread_t nit5;
- pthread_t nit6;
- pthread_cond_init(¬Empty,NULL);
- pthread_cond_init(¬Full,NULL);
- pthread_mutex_init(&mutex,NULL);
- pthread_create(&nit2,NULL,readDatabase,NULL);
- pthread_create(&nit1,NULL,writeDatabase,NULL);
- pthread_create(&nit3,NULL,writeDatabase,NULL);
- pthread_create(&nit4,NULL,writeDatabase,NULL);
- pthread_create(&nit5,NULL,readDatabase,NULL);
- pthread_create(&nit6,NULL,readDatabase,NULL);
- pthread_join(nit1,NULL);
- pthread_join(nit2,NULL);
- pthread_join(nit3,NULL);
- pthread_join(nit4,NULL);
- pthread_mutex_destroy(&mutex);
- pthread_cond_destroy(¬Empty);
- pthread_cond_destroy(¬Full);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement