ConditionVariable.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Function.h>
  8. #include <LibThreading/Mutex.h>
  9. #include <pthread.h>
  10. #include <sys/cdefs.h>
  11. #include <sys/types.h>
  12. namespace Threading {
  13. // A signaling condition variable that wraps over the pthread_cond_* APIs.
  14. class ConditionVariable {
  15. friend class Mutex;
  16. public:
  17. ConditionVariable(Mutex& to_wait_on)
  18. : m_to_wait_on(to_wait_on)
  19. {
  20. auto result = pthread_cond_init(&m_condition, nullptr);
  21. VERIFY(result == 0);
  22. }
  23. ALWAYS_INLINE ~ConditionVariable()
  24. {
  25. auto result = pthread_cond_destroy(&m_condition);
  26. VERIFY(result == 0);
  27. }
  28. // As with pthread APIs, the mutex must be locked or undefined behavior ensues.
  29. ALWAYS_INLINE void wait()
  30. {
  31. auto result = pthread_cond_wait(&m_condition, &m_to_wait_on.m_mutex);
  32. VERIFY(result == 0);
  33. }
  34. ALWAYS_INLINE void wait_while(Function<bool()> condition)
  35. {
  36. while (condition())
  37. wait();
  38. }
  39. // Release at least one of the threads waiting on this variable.
  40. ALWAYS_INLINE void signal()
  41. {
  42. auto result = pthread_cond_signal(&m_condition);
  43. VERIFY(result == 0);
  44. }
  45. // Release all of the threads waiting on this variable.
  46. ALWAYS_INLINE void broadcast()
  47. {
  48. auto result = pthread_cond_broadcast(&m_condition);
  49. VERIFY(result == 0);
  50. }
  51. private:
  52. pthread_cond_t m_condition;
  53. Mutex& m_to_wait_on;
  54. };
  55. }