summaryrefslogtreecommitdiff
path: root/Kernel/WorkQueue.h
blob: 2ce1e35b0215f1859297d922f38e5b767716084e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
 * Copyright (c) 2021, the SerenityOS developers.
 * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Error.h>
#include <AK/IntrusiveList.h>
#include <Kernel/Forward.h>
#include <Kernel/Locking/SpinlockProtected.h>
#include <Kernel/WaitQueue.h>

namespace Kernel {

extern WorkQueue* g_io_work;

class WorkQueue {
    AK_MAKE_NONCOPYABLE(WorkQueue);
    AK_MAKE_NONMOVABLE(WorkQueue);

public:
    static void initialize();

    ErrorOr<void> try_queue(void (*function)(void*), void* data = nullptr, void (*free_data)(void*) = nullptr)
    {
        auto item = new (nothrow) WorkItem; // TODO: use a pool
        if (!item)
            return Error::from_errno(ENOMEM);
        item->function = [function, data, free_data] {
            function(data);
            if (free_data)
                free_data(data);
        };
        do_queue(*item);
        return {};
    }

    template<typename Function>
    ErrorOr<void> try_queue(Function function)
    {
        auto item = new (nothrow) WorkItem; // TODO: use a pool
        if (!item)
            return Error::from_errno(ENOMEM);
        item->function = Function(function);
        do_queue(*item);
        return {};
    }

private:
    explicit WorkQueue(StringView);

    struct WorkItem {
    public:
        IntrusiveListNode<WorkItem> m_node;
        Function<void()> function;
    };

    void do_queue(WorkItem&);

    RefPtr<Thread> m_thread;
    WaitQueue m_wait_queue;
    SpinlockProtected<IntrusiveList<&WorkItem::m_node>> m_items;
};

}