delay.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * File: delay.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 4 décembre 2018
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. #include <pthread.h>
  11. #include "error.h"
  12. #include "delay.h"
  13. /* --- Fonctions privées --- */
  14. /**
  15. * Thread d'attente de la fonction timer
  16. * @param void* La structure timer_data cast en void*
  17. * @return NULL
  18. */
  19. void* delay_thread(void* data){
  20. delay_t* d;
  21. //Recup données
  22. d = (delay_t*) data;
  23. //Detache le thread
  24. if (pthread_detach(pthread_self()) != 0) {
  25. adderror("Impossible de détacher le thread Delay");
  26. return NULL;
  27. }
  28. //Attend le temps indiqué
  29. sleep(d->second);
  30. //Appel callback
  31. if(d->callback(&game[d->game], d->player) != SUCCESS){
  32. adderror("Erreur callback Delay");
  33. }
  34. return NULL;
  35. }
  36. /* --- Fonctions publiques --- */
  37. void delay(int second, int game, int player, int(*callback)(Game*, int)){
  38. pthread_t thread;
  39. delay_t* d = malloc(sizeof(timer_t));
  40. d->second = second;
  41. d->game = game;
  42. d->player = player;
  43. d->callback = callback;
  44. //Creation thread
  45. if (pthread_create(&thread, NULL, delay_thread, d) != 0) {
  46. adderror("Impossible de créer le thread Delay");
  47. }
  48. }