mutex.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "toolkit.h"
  2. #ifndef _WIN32
  3. int toolkit_mutex_init(toolkit_mutex_t* mutex)
  4. {
  5. #if defined(NDEBUG) || !defined(PTHREAD_MUTEX_ERRORCHECK)
  6. if (pthread_mutex_init(mutex, NULL) != 0)
  7. return -1;
  8. return 0;
  9. #else
  10. pthread_mutexattr_t attr;
  11. int err;
  12. if (pthread_mutexattr_init(&attr))
  13. abort();
  14. if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK))
  15. abort();
  16. err = pthread_mutex_init(mutex, &attr);
  17. if (pthread_mutexattr_destroy(&attr))
  18. abort();
  19. return err == 0 ? 0 : -1;
  20. #endif
  21. }
  22. int toolkit_mutex_init_recursive(toolkit_mutex_t* mutex) {
  23. pthread_mutexattr_t attr;
  24. int err;
  25. if (pthread_mutexattr_init(&attr))
  26. abort();
  27. if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE))
  28. abort();
  29. err = pthread_mutex_init(mutex, &attr);
  30. if (pthread_mutexattr_destroy(&attr))
  31. abort();
  32. return err == 0 ? 0 : -1;
  33. }
  34. void toolkit_mutex_destroy(toolkit_mutex_t* mutex) {
  35. if (pthread_mutex_destroy(mutex))
  36. abort();
  37. }
  38. void toolkit_mutex_lock(toolkit_mutex_t* mutex) {
  39. if (pthread_mutex_lock(mutex))
  40. abort();
  41. }
  42. int toolkit_mutex_trylock(toolkit_mutex_t* mutex) {
  43. int err;
  44. err = pthread_mutex_trylock(mutex);
  45. if (err) {
  46. if (err != EBUSY && err != EAGAIN)
  47. abort();
  48. return -1;
  49. }
  50. return 0;
  51. }
  52. void toolkit_mutex_unlock(toolkit_mutex_t* mutex) {
  53. if (pthread_mutex_unlock(mutex))
  54. abort();
  55. }
  56. void toolkit_once(toolkit_once_t* guard, void (*callback)(void)) {
  57. if (pthread_once(guard, callback))
  58. abort();
  59. }
  60. #endif //NOT _WIN32