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