Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <string.h>
- //Struct Létrehozása adattárolás miatt
- typedef struct {
- int ThreadIndex;
- int* Resoults;
- int* Input;
- } inputdata;
- //Függvény prototípusok
- void* Forktask(void* argument);
- void GenerateRand(int upper, int lower, int* tomb );
- int Final(int* tomb);
- int main() {
- srand(time(NULL));
- //pipe változók dekralációja
- int pipes[2];
- pid_t cpid;
- //pipe error kezelés
- if(pipe(pipes) == -1){
- perror("pipe");
- exit(-1);
- }
- //pidek kiiratása
- printf("%d: fd1: %d, fd2: %d\n",getpid(),pipes[0],pipes[1]);
- //gyermek process léthehozása
- cpid = fork();
- if(cpid == -1){
- perror("fork");
- exit(0);
- }
- //gyermek process szálkezelési mechanizmus pipe-ok segítségével
- if(cpid == 0){
- int i;
- int input[1000];
- int Resoults[10] = { 0,0,0,0,0,0,0,0,0 };
- pthread_t Thread[10];
- read(pipes[0], input, sizeof(int) * 1000);
- close(pipes[0]);
- for (i = 0; i < 10; i++){
- inputdata* Active = malloc(sizeof(inputdata));
- Active->ThreadIndex = i;
- Active->Input = input;
- Active->Resoults = Resoults;
- pthread_create(&Thread[i], NULL, Forktask, Active);
- }
- for (i = 0; i < 10; i++){
- pthread_join(Thread[i], NULL);
- }
- write(pipes[1], Resoults, 10 * sizeof(int));
- close(pipes[0]);
- exit(0);
- }
- //szülőprocess szálkezelési mechanizmus pipe-ok segítségével és eredmény meghatározás és kiiratás
- else
- {
- int i;
- int input[1000];
- int Resoults[10];
- GenerateRand(10000, 1000, input);
- write(pipes[1], input, sizeof(int) * 1000);
- read(pipes[0], Resoults, 10 * sizeof(int));
- close(pipes[0]);
- wait(NULL);
- for (i = 0; i < 10; i++) {
- printf("%d.szál eredménye: %d\n", i + 1, Resoults[i]);
- }
- printf("Eredmény :%d\n", Final(Resoults));
- }
- return 0;
- }
- //szálankénti maximum kiválasztás
- void* Forktask(void* arg) {
- inputdata* argument = arg;
- int BeginingIndex = argument->ThreadIndex * 100;
- int EndIndex = BeginingIndex + 100;
- int i;
- for (i = BeginingIndex; i < EndIndex; i++)
- {
- if (argument->Input[i] > argument->Resoults[argument->ThreadIndex]) {
- argument->Resoults[argument->ThreadIndex] = argument->Input[i];
- }
- }
- free(argument);
- pthread_exit(0);
- }
- //random szám generálás a tömbfeltöltés miatt
- void GenerateRand(int upper, int lower, int* tomb) {
- int i;
- for ( i = 0; i < 1000; i++){
- tomb [i] = (rand() % (upper - lower + 1)) + lower;
- }
- }
- //végső legnagyobb elem meghatározása a szálak által pipeon keresztül begyűjtött adatokból
- int Final(int* tomb) {
- int FinalRseaults = 0,i;
- for (i = 0; i < 10; i++){
- if (tomb[i] > FinalRseaults){
- FinalRseaults = tomb[i];
- }
- }
- return FinalRseaults;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement