mutex.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. #if defined(_WIN32)
  11. # include <windows.h>
  12. #else
  13. # include <pthread.h>
  14. #endif
  15. typedef struct {
  16. #if defined(_WIN32)
  17. CRITICAL_SECTION csection;
  18. #else
  19. pthread_mutex_t mutex;
  20. #endif
  21. } mutex_t;
  22. static void
  23. _mutex_initialize(mutex_t* mutex) {
  24. #if defined(_WIN32)
  25. InitializeCriticalSectionAndSpinCount(&mutex->csection, 4000);
  26. #else
  27. pthread_mutexattr_t attr;
  28. pthread_mutexattr_init(&attr);
  29. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  30. pthread_mutex_init(&mutex->mutex, &attr);
  31. pthread_mutexattr_destroy(&attr);
  32. #endif
  33. }
  34. static void
  35. _mutex_finalize(mutex_t* mutex) {
  36. #if defined(_WIN32)
  37. DeleteCriticalSection(&mutex->csection);
  38. #else
  39. pthread_mutex_destroy(&mutex->mutex);
  40. #endif
  41. }
  42. mutex_t*
  43. mutex_allocate(void) {
  44. mutex_t* mutex = (mutex_t*)malloc(sizeof(mutex_t));
  45. _mutex_initialize(mutex);
  46. return mutex;
  47. }
  48. void
  49. mutex_deallocate(mutex_t* mutex) {
  50. if (!mutex)
  51. return;
  52. _mutex_finalize(mutex);
  53. free(mutex);
  54. }
  55. int
  56. mutex_lock(mutex_t* mutex) {
  57. #if defined(_WIN32)
  58. EnterCriticalSection(&mutex->csection);
  59. return 0;
  60. #else
  61. return pthread_mutex_lock(&mutex->mutex);
  62. #endif
  63. }
  64. int
  65. mutex_unlock(mutex_t* mutex) {
  66. #if defined(_WIN32)
  67. LeaveCriticalSection(&mutex->csection);
  68. return 0;
  69. #else
  70. return pthread_mutex_unlock(&mutex->mutex);
  71. #endif
  72. }