mutex.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * simplified from mutex.c from Foundation Library, in the Public Domain
  3. * https://github.com/rampantpixels/foundation_lib/blob/master/foundation/mutex.c
  4. *
  5. * This file is Copyright (C) PyZMQ Developers
  6. * Distributed under the terms of the Modified BSD License.
  7. *
  8. */
  9. #pragma once
  10. #include <stdlib.h>
  11. #if defined(_WIN32)
  12. # include <windows.h>
  13. #else
  14. # include <pthread.h>
  15. #endif
  16. typedef struct {
  17. #if defined(_WIN32)
  18. CRITICAL_SECTION csection;
  19. #else
  20. pthread_mutex_t mutex;
  21. #endif
  22. } mutex_t;
  23. static void
  24. _mutex_initialize(mutex_t* mutex) {
  25. #if defined(_WIN32)
  26. InitializeCriticalSectionAndSpinCount(&mutex->csection, 4000);
  27. #else
  28. pthread_mutexattr_t attr;
  29. pthread_mutexattr_init(&attr);
  30. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  31. pthread_mutex_init(&mutex->mutex, &attr);
  32. pthread_mutexattr_destroy(&attr);
  33. #endif
  34. }
  35. static void
  36. _mutex_finalize(mutex_t* mutex) {
  37. #if defined(_WIN32)
  38. DeleteCriticalSection(&mutex->csection);
  39. #else
  40. pthread_mutex_destroy(&mutex->mutex);
  41. #endif
  42. }
  43. mutex_t*
  44. mutex_allocate(void) {
  45. mutex_t* mutex = (mutex_t*)malloc(sizeof(mutex_t));
  46. _mutex_initialize(mutex);
  47. return mutex;
  48. }
  49. void
  50. mutex_deallocate(mutex_t* mutex) {
  51. if (!mutex)
  52. return;
  53. _mutex_finalize(mutex);
  54. free(mutex);
  55. }
  56. int
  57. mutex_lock(mutex_t* mutex) {
  58. #if defined(_WIN32)
  59. EnterCriticalSection(&mutex->csection);
  60. return 0;
  61. #else
  62. return pthread_mutex_lock(&mutex->mutex);
  63. #endif
  64. }
  65. int
  66. mutex_unlock(mutex_t* mutex) {
  67. #if defined(_WIN32)
  68. LeaveCriticalSection(&mutex->csection);
  69. return 0;
  70. #else
  71. return pthread_mutex_unlock(&mutex->mutex);
  72. #endif
  73. }