/libs/headers/gc/private/darwin_semaphore.h

http://github.com/nddrylliog/ooc · C++ Header · 68 lines · 53 code · 9 blank · 6 comment · 12 complexity · 14a4a64df372dafcc6121c4d958ed00c MD5 · raw file

  1. #ifndef GC_DARWIN_SEMAPHORE_H
  2. #define GC_DARWIN_SEMAPHORE_H
  3. #if !defined(GC_DARWIN_THREADS)
  4. #error darwin_semaphore.h included with GC_DARWIN_THREADS not defined
  5. #endif
  6. /*
  7. This is a very simple semaphore implementation for darwin. It
  8. is implemented in terms of pthreads calls so it isn't async signal
  9. safe. This isn't a problem because signals aren't used to
  10. suspend threads on darwin.
  11. */
  12. typedef struct {
  13. pthread_mutex_t mutex;
  14. pthread_cond_t cond;
  15. int value;
  16. } sem_t;
  17. static int sem_init(sem_t *sem, int pshared, int value) {
  18. int ret;
  19. if(pshared)
  20. GC_abort("sem_init with pshared set");
  21. sem->value = value;
  22. ret = pthread_mutex_init(&sem->mutex,NULL);
  23. if(ret < 0) return -1;
  24. ret = pthread_cond_init(&sem->cond,NULL);
  25. if(ret < 0) return -1;
  26. return 0;
  27. }
  28. static int sem_post(sem_t *sem) {
  29. if(pthread_mutex_lock(&sem->mutex) < 0)
  30. return -1;
  31. sem->value++;
  32. if(pthread_cond_signal(&sem->cond) < 0) {
  33. pthread_mutex_unlock(&sem->mutex);
  34. return -1;
  35. }
  36. if(pthread_mutex_unlock(&sem->mutex) < 0)
  37. return -1;
  38. return 0;
  39. }
  40. static int sem_wait(sem_t *sem) {
  41. if(pthread_mutex_lock(&sem->mutex) < 0)
  42. return -1;
  43. while(sem->value == 0) {
  44. pthread_cond_wait(&sem->cond,&sem->mutex);
  45. }
  46. sem->value--;
  47. if(pthread_mutex_unlock(&sem->mutex) < 0)
  48. return -1;
  49. return 0;
  50. }
  51. static int sem_destroy(sem_t *sem) {
  52. int ret;
  53. ret = pthread_cond_destroy(&sem->cond);
  54. if(ret < 0) return -1;
  55. ret = pthread_mutex_destroy(&sem->mutex);
  56. if(ret < 0) return -1;
  57. return 0;
  58. }
  59. #endif