Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- #include <time.h>
- #include <sys/wait.h>
- #include <fcntl.h>
- #include <unistd.h>
- //amount of data in source array
- #define N 32
- // K defenition from task
- #define K 5
- // maximum integer in source array
- #define MAX 128
- #define THREADS 4
- struct equation {
- int a;
- int b;
- };
- int *array;
- struct equation res[THREADS];
- int res_max[THREADS];
- int pids[THREADS][2];
- void generate_array()
- {
- srand(time(NULL));
- int i;
- array = (int *)malloc(sizeof(int)*N);
- for (i=0;i<N;i++)
- {
- array[i] = rand() % MAX;
- }
- }
- void print(int *data)
- {
- int i;
- for(i=0;i<N;i++)
- {
- printf("%i ", data[i]);
- }
- printf("\n");
- }
- struct equation make_equation(int a, int b)
- {
- return *(struct equation[]){{a,b}};
- }
- int main(void)
- {
- // loop index
- int i,j;
- pid_t p_id;
- // equation variables:
- int a,b;
- // if (THREADS < 4)
- // {
- // fprintf(stderr, "Minimum threads are: 4. Your's: %i\n", THREADS);
- // exit(1);
- // }
- generate_array();
- print(array);
- printf("K: %i\n\n", K);
- int max = -1;
- struct equation tmp;
- for (p_id=0;p_id<THREADS;p_id++)
- {
- pipe(pids[p_id]);
- pid_t pid = fork(); // <<<<-------------- FORK!!!
- if (pid == 0)
- {//child
- for(i=0;i<N;++i)
- {
- for(j=p_id;j<N;j+=THREADS)
- {
- a = array[i];
- b = array[j];
- if (b-a == K)
- {
- if (max < abs(a) * abs(b))
- {
- max = abs(a) * abs(b);
- tmp.a = a;
- tmp.b = b;
- }
- }
- }
- }
- // printf("|%i|*|%i| = %i\n", tmp.a, tmp.b, max);
- char buf[4096];
- sprintf(buf, "%i;%i;%i", tmp.a,tmp.b,max);
- close(pids[p_id][0]);
- write(pids[p_id][1], buf, 4096);
- // printf("Sended\n");
- return 0; //stopping child
- }else{
- //parent
- usleep(150); // for pretty printf :)
- }
- }
- //parent
- max = -1;
- tmp = *(struct equation[]){{0,0}};
- pid_t tmp_pid;
- for (p_id=0;p_id<THREADS;p_id++)
- {
- wait(NULL);
- char buf[4096];
- close(pids[p_id][1]);
- read(pids[p_id][0],buf, 4096);
- sscanf(buf, "%i;%i;%i", &res[p_id].a, &res[p_id].b, &res_max[p_id]);
- printf("th: %i Received: |%i|*|%i| = %i\n", p_id, res[p_id].a, res[p_id].b, res_max[p_id]);
- if (max < abs(res[p_id].a) * abs(res[p_id].b))
- {
- max = abs(res[p_id].a) * abs(res[p_id].b);
- tmp = *(struct equation[]){{res[p_id].a,res[p_id].b}};
- tmp_pid = p_id;
- }
- }
- printf("Max found\n");
- printf("|%i| * |%i| = %i\n", res[tmp_pid].a, res[tmp_pid].b, max);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement