Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. /*
  2. 1. Napisz rozwiązanie problemu pięciu filozofów z możliwością blokady.
  3. Zaimplementuj pięć widelców przy pomocy pięcioelementowej tablicy muteksów
  4. (funkcje pthread_mutex_lock i pthread_mutex_unlock).
  5. W rozwiązaniu tym filozof o numerze i=0...4 podnosi najpierw widelec lewy
  6. (o numerze i) a następnie widelec prawy (o numerze (i+1)%5).
  7. Zademonstruj prowadzącemu wystąpienie zjawiska blokady.
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <pthread.h>
  12. #include <unistd.h>
  13.  
  14. pthread_mutex_t forks[5];
  15. #define N 5
  16.  
  17. struct arg_struct {
  18. int position;
  19. const char* name;
  20. };
  21.  
  22. void* function(void* philosophers_info)
  23. {
  24. struct arg_struct* philosopher = (struct arg_struct*)philosophers_info;
  25. const char* philospher_name = (char*) philosopher->name;
  26. int n = (long) philosopher->position;
  27. while(1)
  28. {
  29. printf("%s is thinking\n",philospher_name);
  30.  
  31. pthread_mutex_lock(&forks[n]);
  32. pthread_mutex_lock(&forks[(n+1)%N]);
  33.  
  34. printf("%s is eating\n",philospher_name);
  35.  
  36. pthread_mutex_unlock(&forks[n]);
  37. pthread_mutex_unlock(&forks[(n+1)%N]);
  38.  
  39. }
  40. }
  41.  
  42. int main(int argc, char* argv[])
  43. {
  44. int i;
  45. const char *philosophers_names[] = {"Jean-Paul Sartre", "Albert Camus", "Michel Foucault", "Simone de Beauvoir", "Jacques Derrida"};
  46. pthread_t philosophers[5];
  47. struct arg_struct *philosophers_info = malloc(sizeof(struct arg_struct)*N);
  48. for (i=0;i<N;i++)
  49. {
  50. pthread_mutex_init(&forks[i], NULL);
  51. }
  52.  
  53. for (i=0;i<N;i++)
  54. {
  55. philosophers_info[i].position = i;
  56. philosophers_info[i].name = philosophers_names[i];
  57. pthread_create(&philosophers[i], NULL, &function, (void*)&philosophers_info[i]);
  58. }
  59.  
  60. for (i=0;i<N;i++)
  61. {
  62. pthread_join(philosophers[i],NULL);
  63. }
  64.  
  65. for (i=0;i<N;i++)
  66. {
  67. pthread_mutex_destroy(&forks[i]);
  68. }
  69. exit(EXIT_SUCCESS);
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement