counter.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <grass/config.h>
  2. #ifdef HAVE_PTHREAD_H
  3. #define _XOPEN_SOURCE 500
  4. #endif
  5. #include <grass/gis.h>
  6. #ifdef HAVE_PTHREAD_H
  7. #include <pthread.h>
  8. static pthread_mutex_t mutex;
  9. #endif
  10. #ifdef HAVE_PTHREAD_H
  11. static void make_mutex(void)
  12. {
  13. static pthread_mutex_t t_mutex = PTHREAD_MUTEX_INITIALIZER;
  14. static int initialized;
  15. pthread_mutexattr_t attr;
  16. if (initialized)
  17. return;
  18. pthread_mutex_lock(&t_mutex);
  19. if (initialized) {
  20. pthread_mutex_unlock(&t_mutex);
  21. return;
  22. }
  23. pthread_mutexattr_init(&attr);
  24. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  25. pthread_mutex_init(&mutex, &attr);
  26. initialized = 1;
  27. pthread_mutex_unlock(&t_mutex);
  28. }
  29. #endif
  30. void G_init_counter(struct Counter *c, int v)
  31. {
  32. #ifdef HAVE_PTHREAD_H
  33. make_mutex();
  34. #endif
  35. c->value = v;
  36. }
  37. int G_counter_next(struct Counter *c)
  38. {
  39. int v;
  40. #ifdef HAVE_PTHREAD_H
  41. pthread_mutex_lock(&mutex);
  42. #endif
  43. v = c->value++;
  44. #ifdef HAVE_PTHREAD_H
  45. pthread_mutex_unlock(&mutex);
  46. #endif
  47. return v;
  48. }
  49. int G_is_initialized(int *p)
  50. {
  51. if (*p)
  52. return 1;
  53. #ifdef HAVE_PTHREAD_H
  54. make_mutex();
  55. pthread_mutex_lock(&mutex);
  56. if (*p) {
  57. pthread_mutex_unlock(&mutex);
  58. return 1;
  59. }
  60. #endif
  61. return 0;
  62. }
  63. void G_initialize_done(int *p)
  64. {
  65. *p = 1;
  66. #ifdef HAVE_PTHREAD_H
  67. pthread_mutex_unlock(&mutex);
  68. #endif
  69. }