1/*
2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef ES2PANDA_UTIL_WORKERQUEUE_H
17#define ES2PANDA_UTIL_WORKERQUEUE_H
18
19#include <es2panda.h>
20#include <macros.h>
21#include <os/thread.h>
22
23#include <condition_variable>
24#include <mutex>
25
26namespace panda::es2panda::util {
27
28class WorkerJob {
29public:
30    explicit WorkerJob() {};
31    NO_COPY_SEMANTIC(WorkerJob);
32    NO_MOVE_SEMANTIC(WorkerJob);
33    virtual ~WorkerJob() = default;
34
35    virtual void Run() = 0;
36    void DependsOn(WorkerJob *job);
37    void Signal();
38
39protected:
40    std::mutex m_;
41    std::condition_variable cond_;
42    std::vector<WorkerJob *> dependants_ {};
43    size_t dependencies_ {0};
44};
45
46class WorkerQueue {
47public:
48    explicit WorkerQueue(size_t threadCount);
49    NO_COPY_SEMANTIC(WorkerQueue);
50    NO_MOVE_SEMANTIC(WorkerQueue);
51    virtual ~WorkerQueue();
52
53    virtual void Schedule() = 0;
54    void Consume();
55    void Wait();
56
57protected:
58    static void Worker(WorkerQueue *queue);
59
60    std::vector<os::thread::native_handle_type> threads_;
61    std::vector<Error> errors_;
62    std::mutex m_;
63    std::condition_variable jobsAvailable_;
64    std::condition_variable jobsFinished_;
65    std::vector<WorkerJob *> jobs_ {};
66    size_t jobsCount_ {0};
67    size_t activeWorkers_ {0};
68    bool terminate_ {false};
69};
70}  // namespace panda::es2panda::util
71
72#endif
73