Tobiahao

S01_WATKI_03

Dec 19th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. /*
  2. Zmodyfikuj program opisany wyżej tak, aby wątki zwracały jak rezultaty swojego działania wyli-
  3. czone wyniki do wątku głównego, który będzie wypisywał je na ekran.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <pthread.h>
  9.  
  10. struct number {
  11.     int x, y;
  12. };
  13.  
  14. void *add_thread_function(void *arg)
  15. {
  16.     struct number *buffer = arg;
  17.     int *pointer_buffer = (int *)malloc(sizeof(int));
  18.     *pointer_buffer = buffer->x+buffer->y;
  19.     pthread_exit((void *)pointer_buffer);
  20. }
  21.  
  22. void *subtract_thread_function(void *arg)
  23. {
  24.     struct number *buffer = arg;
  25.     int *pointer_buffer = (int *)malloc(sizeof(int));
  26.     *pointer_buffer = buffer->x-buffer->y;
  27.     pthread_exit((void *)pointer_buffer);
  28. }
  29.  
  30. int main(void)
  31. {
  32.     pthread_t add_thread, subtract_thread;
  33.     struct number *num;
  34.     void *add_return_pointer, *subtract_return_pointer;
  35.     int add_result, subtract_result;
  36.    
  37.     num->x = 5;
  38.     num->y = 3;
  39.  
  40.     pthread_create(&add_thread, NULL, add_thread_function, (void *)num);
  41.     pthread_create(&subtract_thread, NULL, subtract_thread_function, (void *)num);
  42.  
  43.     pthread_join(add_thread, &add_return_pointer);
  44.     pthread_join(subtract_thread, &subtract_return_pointer);
  45.  
  46.     add_result = *((int *)add_return_pointer);
  47.     subtract_result = *((int *)subtract_return_pointer);
  48.  
  49.     printf("Dodawanie: %d\nOdejmowanie: %d\n", add_result, subtract_result);
  50.  
  51.     return EXIT_SUCCESS;
  52. }
Add Comment
Please, Sign In to add comment