1/*
2 * Copyright (c) 2021 - 2024 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_COMPILER_CORE_COMPILE_QUEUE_H
17#define ES2PANDA_COMPILER_CORE_COMPILE_QUEUE_H
18
19#include "macros.h"
20#include "os/thread.h"
21#include "es2panda.h"
22#include "compiler/core/compileJob.h"
23
24#include <condition_variable>
25#include <functional>
26#include <mutex>
27
28namespace ark::es2panda::varbinder {
29class FunctionScope;
30}  // namespace ark::es2panda::varbinder
31
32namespace ark::es2panda::public_lib {
33struct Context;
34}  // namespace ark::es2panda::public_lib
35
36namespace ark::es2panda::compiler {
37
38class CompileQueue {
39public:
40    using JobsFinishedCb = std::function<void(CompileJob *)>;
41
42    explicit CompileQueue(size_t threadCount);
43    NO_COPY_SEMANTIC(CompileQueue);
44    NO_MOVE_SEMANTIC(CompileQueue);
45    ~CompileQueue();
46
47    void Schedule(public_lib::Context *context);
48    void Consume();
49    void Wait(const JobsFinishedCb &onFinishedCb);
50
51private:
52    static void Worker(CompileQueue *queue);
53
54    std::vector<os::thread::NativeHandleType> threads_;
55    std::vector<Error> errors_;
56    std::mutex m_;
57    std::condition_variable jobsAvailable_;
58    std::condition_variable jobsFinished_;
59    CompileJob *jobs_ {};
60    size_t jobsCount_ {0};
61    size_t totalJobsCount_ {0};
62    size_t activeWorkers_ {0};
63    bool terminate_ {};
64};
65}  // namespace ark::es2panda::compiler
66
67#endif
68