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