• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 #ifndef OHOS_APP_DISPATCHER_GROUP_IMPL_H
16 #define OHOS_APP_DISPATCHER_GROUP_IMPL_H
17 
18 #include <atomic>
19 #include <deque>
20 #include <mutex>
21 #include <condition_variable>
22 #include "group.h"
23 #include "runnable.h"
24 
25 namespace OHOS {
26 namespace AppExecFwk {
27 /**
28  *  A group used to associated with tasks.
29  */
30 class GroupImpl : public Group {
31 public:
32     GroupImpl();
33 
34     ~GroupImpl() = default;
35     /**
36      *  Wait all tasks associated to this group to be done.
37      *  @param timeout is the max waiting time for jobs in group execute, in ms.
38      *  @return true if successfully wait.
39      */
40     bool AwaitAllTasks(long timeout);
41 
42     /**
43      *  Associates a task to this group.
44      */
45     void Associate();
46 
47     /**
48      *  Notify group that a task is done or canceled.
49      */
50     void NotifyTaskDone();
51 
52     /**
53      *  Adds the |notification| to notification list.
54      *  If all tasks are already done, |notification| will immediately be called on current thread.
55      *  Attention: If tasks are added just this time, it may not be considered.
56      *  @param notification Called when all tasks done.
57      */
58     bool AddNotification(const std::shared_ptr<Runnable> &notification);
59 
60 private:
61     const static int MAX_TASK = 1000;
62     std::atomic<int> count_;
63     std::deque<std::shared_ptr<Runnable>> notifications_;
64     std::mutex dataMutex_;
65     std::condition_variable condition_;
66 
67 private:
68     /**
69      *  Notify all tasks and remove from queue.
70      *  Attention: Notifications added after all tasks done is not guaranteed.
71      */
72     void DrainNotifications();
73 };
74 }  // namespace AppExecFwk
75 }  // namespace OHOS
76 #endif
77