Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #include "unistd.h"
- #include "pthread.h"
- #include "stdlib.h"
- #include "errno.h"
- #include "limits.h"
- #include "math.h"
- #include "semaphore.h"
- #include "string.h"
- #define BUFFER_SIZE 100
- sem_t wr, rd1, rd2, rd3;
- void emptyBuffer( char* buff);
- void *threadCzytelnik(void *arg);
- struct targs{
- int numWatku;
- };
- char common[BUFFER_SIZE];
- int koniecPliku = 0;
- int main()
- {
- FILE *fp;
- emptyBuffer(common);
- sem_init(&wr, 0, 1);
- sem_init(&rd1, 0, 0);
- sem_init(&rd2, 0, 0);
- sem_init(&rd3, 0, 0);
- pthread_attr_t attrs;
- pthread_attr_init(&attrs);
- //pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED );
- pthread_t threadId[3];
- fp = fopen("/etc/passwd","r");
- struct targs watki[3];
- {
- int i = 0;
- for(;i < 3; i++)
- {
- watki[i].numWatku = i+1;
- pthread_create(&threadId[i], &attrs, threadCzytelnik, &watki[i]);
- pthread_detach(threadId[i]);
- }
- }
- char *l;
- while( 1 ) {
- sem_wait(&wr);
- l = fgets(common, BUFFER_SIZE, fp);
- if(l==0) break;
- sem_post(&rd1);
- }
- fclose(fp);
- koniecPliku = 1;
- sem_post(&rd1);
- }
- void emptyBuffer( char* buff)
- {
- {
- int i = 0;
- for(;i<BUFFER_SIZE;i++)
- {
- buff[i] = 0;
- }
- }
- }
- void *threadCzytelnik(void *arg)
- {
- struct targs *argptr = (struct targs*) arg;
- char nazwaPliku[80];
- snprintf(nazwaPliku, 80, "./MATEUSZ%d", argptr->numWatku);
- FILE *fp = fopen(nazwaPliku, "w");
- while(1)
- {
- if(argptr->numWatku==1) sem_wait(&rd1);
- if(argptr->numWatku==2) sem_wait(&rd2);
- if(argptr->numWatku==3) sem_wait(&rd3);
- if(koniecPliku)
- {
- fflush(fp);
- fclose(fp);
- pthread_exit(0);
- }
- fwrite(common, sizeof(char), strlen(common), fp);
- printf("%d-%s\n", argptr->numWatku, common);
- fflush(stdout);
- if(argptr->numWatku==1) sem_post(&rd2);
- if(argptr->numWatku==2) sem_post(&rd3);
- if(argptr->numWatku==3) sem_post(&wr);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement