ConditionVariable.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/types.h>
  11. namespace Threading {
  12. // A signaling condition variable that wraps over the pthread_cond_* APIs.
  13. class ConditionVariable {
  14. friend class Mutex;
  15. public:
  16. ConditionVariable(Mutex& to_wait_on)
  17. : m_to_wait_on(to_wait_on)
  18. {
  19. auto result = pthread_cond_init(&m_condition, nullptr);
  20. VERIFY(result == 0);
  21. }
  22. ALWAYS_INLINE ~ConditionVariable()
  23. {
  24. auto result = pthread_cond_destroy(&m_condition);
  25. VERIFY(result == 0);
  26. }
  27. // As with pthread APIs, the mutex must be locked or undefined behavior ensues.
  28. ALWAYS_INLINE void wait()
  29. {
  30. auto result = pthread_cond_wait(&m_condition, &m_to_wait_on.m_mutex);
  31. VERIFY(result == 0);
  32. }
  33. ALWAYS_INLINE void wait_while(Function<bool()> condition)
  34. {
  35. while (condition())
  36. wait();
  37. }
  38. // Release at least one of the threads waiting on this variable.
  39. ALWAYS_INLINE void signal()
  40. {
  41. auto result = pthread_cond_signal(&m_condition);
  42. VERIFY(result == 0);
  43. }
  44. // Release all of the threads waiting on this variable.
  45. ALWAYS_INLINE void broadcast()
  46. {
  47. auto result = pthread_cond_broadcast(&m_condition);
  48. VERIFY(result == 0);
  49. }
  50. private:
  51. pthread_cond_t m_condition;
  52. Mutex& m_to_wait_on;
  53. };
  54. }