delay.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #include "bomberstudent_server.h"
  14. /* --- Extern --- */
  15. extern Game game[MAXGAME];
  16. extern int nbGame;
  17. extern pthread_mutex_t gameMutex[MAXGAME];
  18. extern pthread_mutex_t playerMutex[MAXGAME * MAXPLAYER];
  19. /* --- Fonctions privées --- */
  20. /**
  21. * Thread d'attente de la fonction timer
  22. * @param void* La structure timer_data cast en void*
  23. * @return NULL
  24. */
  25. void* delay_thread(void* data) {
  26. delay_t* d;
  27. //Recup données
  28. d = (delay_t*) data;
  29. //Detache le thread
  30. if (pthread_detach(pthread_self()) != 0) {
  31. adderror("Impossible de détacher le thread Delay");
  32. return NULL;
  33. }
  34. //Attend le temps indiqué
  35. sleep(d->second);
  36. //Appel callback
  37. pthread_mutex_lock(&gameMutex[d->game]);
  38. if (game[d->game].active) {
  39. pthread_mutex_lock(&playerMutex[(d->game * MAXPLAYER) + d->player]);
  40. if (game[d->game].player[d->player]->ini) {
  41. if (d->callback(&game[d->game], d->player) != SUCCESS) {
  42. adderror("Erreur callback Delay");
  43. }
  44. }
  45. pthread_mutex_unlock(&playerMutex[(d->game * MAXPLAYER) + d->player]);
  46. }
  47. pthread_mutex_unlock(&gameMutex[d->game]);
  48. return NULL;
  49. }
  50. /* --- Fonctions publiques --- */
  51. void delay(int second, int game, int player, int(*callback)(Game*, int)) {
  52. pthread_t thread;
  53. delay_t* d = malloc(sizeof (timer_t));
  54. d->second = second;
  55. d->game = game;
  56. d->player = player;
  57. d->callback = callback;
  58. //Creation thread
  59. if (pthread_create(&thread, NULL, delay_thread, d) != 0) {
  60. adderror("Impossible de créer le thread Delay");
  61. }
  62. }
  63. int callback_major_end(Game* g, int playerIndex) {
  64. JsonEncoder notif;
  65. //Retire le bonus major
  66. g->player[playerIndex]->major = 0;
  67. //Creation json
  68. ini_encoder(&notif);
  69. describe_player(g->player[playerIndex], &notif);
  70. //Envoi
  71. if (!notify_client(g->player[playerIndex]->cli, "POST", "player/major/end", &notif)) {
  72. return FAIL;
  73. }
  74. return SUCCESS;
  75. }