Coverage Report

Created: 2025-12-18 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibThreading/ConditionVariable.h
Line
Count
Source
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
14
namespace Threading {
15
16
// A signaling condition variable that wraps over the pthread_cond_* APIs.
17
class ConditionVariable {
18
    friend class Mutex;
19
20
public:
21
    ConditionVariable(Mutex& to_wait_on)
22
33
        : m_to_wait_on(to_wait_on)
23
33
    {
24
33
        auto result = pthread_cond_init(&m_condition, nullptr);
25
33
        VERIFY(result == 0);
26
33
    }
27
28
    ALWAYS_INLINE ~ConditionVariable()
29
33
    {
30
33
        auto result = pthread_cond_destroy(&m_condition);
31
33
        VERIFY(result == 0);
32
33
    }
33
34
    // As with pthread APIs, the mutex must be locked or undefined behavior ensues.
35
    ALWAYS_INLINE void wait()
36
75
    {
37
75
        auto result = pthread_cond_wait(&m_condition, &m_to_wait_on.m_mutex);
38
75
        VERIFY(result == 0);
39
75
    }
40
    ALWAYS_INLINE void wait_while(Function<bool()> condition)
41
0
    {
42
0
        while (condition())
43
0
            wait();
44
0
    }
45
    // Release at least one of the threads waiting on this variable.
46
    ALWAYS_INLINE void signal()
47
0
    {
48
0
        auto result = pthread_cond_signal(&m_condition);
49
0
        VERIFY(result == 0);
50
0
    }
51
    // Release all of the threads waiting on this variable.
52
    ALWAYS_INLINE void broadcast()
53
132
    {
54
132
        auto result = pthread_cond_broadcast(&m_condition);
55
132
        VERIFY(result == 0);
56
132
    }
57
58
private:
59
    pthread_cond_t m_condition;
60
    Mutex& m_to_wait_on;
61
};
62
63
}