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
- pthread_mutex_t mut[4];
- 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);
- for(int i = 0; i < 4; i++)
- pthread_mutex_init(&mut[i], NULL);
- 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]);
- }
- }
- pthread_mutex_lock(&mut[1]);
- pthread_mutex_lock(&mut[2]);
- pthread_mutex_lock(&mut[3]);
- char *l;
- int i = 0;
- while( 1 ) {
- pthread_mutex_lock(&mut[0]);
- l = fgets(common, BUFFER_SIZE, fp);
- if(l==0) break;
- pthread_mutex_unlock(&mut[1]);
- }
- fclose(fp);
- koniecPliku = 1;
- }
- 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];
- int num = argptr->numWatku;
- snprintf(nazwaPliku, 80, "./MATEUSZ%d", num);
- FILE *fp = fopen(nazwaPliku, "w");
- while(1)
- {
- pthread_mutex_lock(&mut[num]);
- 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);
- pthread_mutex_unlock(&mut[(num + 1)%4]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement