Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <pthread.h>
  5. #include <errno.h>
  6. #include <stdlib.h>
  7.  
  8.  
  9. void *square(void *x) //funkcja obliczająca wartość kwadratu
  10. {
  11. int threadRetValue = *((int*) x) * *((int*) x);
  12. return (void*)threadRetValue;
  13. }
  14.  
  15. int main(int argc, char** argv)
  16. {
  17.  
  18. pthread_t thread[argc]; // deklaracja wątków
  19. void *readThread; // przechowuje wskaźnik na adres
  20. int EndRes = 0; // deklaracja zmiennej przechowującej wynik końcowy
  21. int tab[argc]; // deklaracja tablicy w celu odczytania wartosci na wejsciu standardowym
  22. int i;
  23. for(i=0 ; i<argc ; i++) // petla w ktorej odbywa sie przypisywanie argumentow do tablicy
  24. {
  25. tab[i] = atoi(argv[i]);
  26. }
  27.  
  28. for( i=1; i<argc ; i++){ // stworzenie odpowiedniej liczby watkow, tyle watkow ile jest argumentow
  29. if(pthread_create(&thread[i], NULL, &square, &tab[i])) //stworzenie wątków i przypisanie im funkcji którą mają wykonać (square)
  30. {
  31. printf("Error when starting a thread."); //Komunikat wyświetlany w wypadku niepowodzenia przy tworzeniu wątku
  32. };
  33. }
  34. int w; // to nie wiem czy potrzebne
  35. for( i=1; i<argc ; i++){
  36. if(pthread_join(thread[i], &readThread)) //czekanie na zakończenie wątku
  37. {
  38. printf("Error when ending a thread."); //Komunikat wyświetlany w wypadku niepowodzenia przy kończeniu pracy wątku
  39. };
  40.  
  41. EndRes += (int)readThread; // obliczanie sumy końcowej
  42. printf("%d:%ld:%d:%s:%d\n",i, thread[i] ,getpid(), argv[i], (int)readThread);
  43. }
  44.  
  45. printf("%s:%ld:%d:%d\n","thread_glowny", pthread_self() ,getpid(), EndRes); // wyświetlanie informacji i sumy końcowej
  46.  
  47. return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement