Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <time.h>
- #define REENTRANT // informacja dla procesora ze aplikacja jest wielowatkowa
- int create_th1;
- int create_th2;
- int create_th3;
- int join_th1;
- int join_th2;
- int join_th3;
- int detach_th1;
- int detach_th2;
- int detach_th3;
- typedef struct _th1 {
- int tab[10];
- int sum;
- }_TH1;
- typedef struct _th2 {
- int tab[2][10];
- int sum;
- int n;
- }_TH2;
- void* _sum1(void* _th1) {
- _TH1 * th1 = (_TH1*)_th1;
- int i;
- for(i = 0; i < 10; i++)
- th1->sum += th1->tab[i];
- pthread_exit(0);
- }
- void* _sum2(void* _th2) {
- _TH2* th2 = (_TH2*)_th2;
- int i,j,count = th2->n;
- for(i = 0;i < 2; i++)
- for(j = 0;j < count;j++)
- th2->sum += th2->tab[i][j];
- pthread_exit(0);
- }
- int main() {
- id_self = pthread_self();
- srand(time(NULL));
- pthread_t id_th1;
- pthread_t id_th2;
- pthread_t id_th3;
- _TH1 th1,th2;
- _TH2 th3;
- th1.sum = 0; th2.sum = 0;
- th3.sum = 0;
- th3.n=3;
- int _tab[2][10];
- int i,j;
- printf("* id main thread: %d\n", id_self);
- for(i=0; i<2; i++){
- for(j=0; j<10; j++){
- _tab[i][j] = rand() % 10;//generowanie liczb losowych do macierzy
- printf("%d ",_tab[i][j]);
- th3.tab[i][j]=_tab[i][j];
- th1.tab[i]=_tab[0][j];//przypisywanie do struktur
- th2.tab[j]=_tab[1][j];// -||-
- }
- /*printf("[s]: wykonuje funkcje pthread_create oraz pthread_join... x2\n");*/
- create_th1=pthread_create(&id_th1, NULL, _sum1, &th1);
- if(create_th1==-1) perror("create1-error");
- join_th1=pthread_join(id_th1, NULL);
- if(join_th1==-1) perror("join1-error");
- create_th2=pthread_create(&id_th2, NULL, _sum1, &th2);
- if(create_th2 == -1) perror("create2-error");
- join_th2=pthread_join(id_th2, NULL);
- if(join_th2==-1) perror("join2-error");
- create_th3=pthread_create(&id_th3, NULL, _sum2, &th3);
- if(create_th3 == -1) perror("create3-error");
- join_th1=pthread_join(id_th3, NULL);
- if(join_th3==-1) perror("join3-error");
- /*printf("[s]: zakonczylem tworzenie i przylaczanie watkow... x2\n");*/
- printf("Sum of first row: %d\n",th1.sum);
- printf("Suma drugiego wiersza: %d\n",th2.sum);
- printf("Suma calkowita: %d\n",th2.sum+th1.sum);
- printf("Suma n-pierwszych elementow danej tablicy: %d\n",th3.sum);
- detach_th1=pthread_detach(id_th1);
- if(detach_th1==-1) perror("detach1-error");
- detach_th2=pthread_detach(id_th2);
- if(detach_th2==-1) perror("detach2-error");
- detach_th3=pthread_detach(id_th3);
- if(detach_th3==-1) perror("detach3-error");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement