thread.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* libanode: the Anode C reference implementation
  2. * Copyright (C) 2009-2010 Adam Ierymenko <[email protected]>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>. */
  16. #include "thread.h"
  17. #include <stdlib.h>
  18. #ifdef WINDOWS
  19. #else /* not WINDOWS */
  20. struct _AnodeThread
  21. {
  22. void (*func)(void *);
  23. void *arg;
  24. int wait_for_join;
  25. pthread_t thread;
  26. };
  27. static void *_AnodeThread_main(void *arg)
  28. {
  29. ((struct _AnodeThread *)arg)->func(((struct _AnodeThread *)arg)->arg);
  30. if (!((struct _AnodeThread *)arg)->wait_for_join)
  31. free(arg);
  32. return (void *)0;
  33. }
  34. AnodeThread *AnodeThread_create(void (*func)(void *),void *arg,int wait_for_join)
  35. {
  36. struct _AnodeThread *t = malloc(sizeof(struct _AnodeThread));
  37. t->func = func;
  38. t->arg = arg;
  39. t->wait_for_join = wait_for_join;
  40. pthread_create(&t->thread,(const pthread_attr_t *)0,&_AnodeThread_main,(void *)t);
  41. if (!wait_for_join)
  42. pthread_detach(t->thread);
  43. return (AnodeThread *)t;
  44. }
  45. void AnodeThread_join(AnodeThread *thread)
  46. {
  47. pthread_join(((struct _AnodeThread *)thread)->thread,(void **)0);
  48. free((void *)thread);
  49. }
  50. #endif /* WINDOWS / not WINDOWS */