ThreadQueue.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "ThreadQueue.h"
  2. #include <assert.h>
  3. #include <time.h>
  4. static inline __attribute__((always_inline))
  5. void get_exceed_time(struct timespec* ptime, long delay)
  6. {
  7. clock_gettime(CLOCK_REALTIME, ptime);
  8. ptime->tv_nsec += delay;
  9. if (ptime->tv_nsec >= 1000000000L) // overflow
  10. {
  11. ptime->tv_nsec -= 1000000000L;
  12. ++ptime->tv_sec;
  13. }
  14. }
  15. ThreadQueue::ThreadQueue()
  16. {
  17. buffer.reserve(256 * sizeof(void *));
  18. sem_init(&event, 0, 0);
  19. }
  20. ThreadQueue::~ThreadQueue()
  21. {
  22. sem_destroy(&event);
  23. }
  24. void ThreadQueue::Queue(const void *in)
  25. {
  26. buffer.write(&in, sizeof(in));
  27. sem_post(&event);
  28. }
  29. void *ThreadQueue::Get()
  30. {
  31. sem_wait(&event);
  32. void *out=0;
  33. size_t read = buffer.read(&out, sizeof(out));
  34. assert(read == sizeof(out));
  35. return out;
  36. }
  37. int ThreadQueue::Wait(long delay, void **val)
  38. {
  39. timespec t;
  40. get_exceed_time(&t, delay);
  41. int ret = sem_timedwait(&event, &t);
  42. if (ret == 0)
  43. {
  44. size_t read = buffer.read(val, sizeof(*val));
  45. assert(read == sizeof(*val));
  46. }
  47. return ret;
  48. }
  49. int ThreadQueue::Try(void **val)
  50. {
  51. int ret = sem_trywait(&event);
  52. if (ret == 0)
  53. {
  54. size_t read = buffer.read(val, sizeof(*val));
  55. assert(read == sizeof(*val));
  56. }
  57. return ret;
  58. }