• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 LIBPANDABASE_UTILS_WORKERQUEUE_H
17 #define LIBPANDABASE_UTILS_WORKERQUEUE_H
18 
19 #include <macros.h>
20 #include <os/thread.h>
21 
22 #include <condition_variable>
23 #include <mutex>
24 
25 namespace panda {
26 class WorkerJob {
27 public:
WorkerJob()28     explicit WorkerJob() {};
29     NO_COPY_SEMANTIC(WorkerJob);
30     NO_MOVE_SEMANTIC(WorkerJob);
31     virtual ~WorkerJob() = default;
32 
33     virtual bool Run() = 0;
34     void DependsOn(WorkerJob *job);
35     void Signal();
36 
37 protected:
38     std::mutex m_;
39     std::condition_variable cond_;
40     std::vector<WorkerJob *> dependants_ {};
41     size_t dependencies_ {0};
42 };
43 
44 class WorkerQueue {
45 public:
46     explicit WorkerQueue(size_t threadCount);
47     NO_COPY_SEMANTIC(WorkerQueue);
48     NO_MOVE_SEMANTIC(WorkerQueue);
49     virtual ~WorkerQueue();
50 
51     virtual void Schedule() = 0;
52 
53     bool Consume();
54     void Wait();
55 
56 protected:
57     static bool Worker(WorkerQueue *queue);
58 
59     std::vector<os::thread::native_handle_type> threads_;
60     std::mutex m_;
61     std::condition_variable jobsAvailable_;
62     std::condition_variable jobsFinished_;
63     std::vector<WorkerJob *> jobs_ {};
64     size_t jobsCount_ {0};
65     size_t activeWorkers_ {0};
66     bool terminate_ {false};
67 };
68 }  // namespace panda
69 
70 #endif
71