• 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 
16 #include "invoker_factory.h"
17 
18 #include <memory>
19 #include <utility>
20 
21 #include "__mutex_base"
22 #include "functional"
23 #include "iremote_invoker.h"
24 #include "unordered_map"
25 
26 namespace OHOS {
27 #ifdef CONFIG_IPC_SINGLE
28 namespace IPC_SINGLE {
29 #endif
30 bool InvokerFactory::isAvailable_ = true;
31 
InvokerFactory()32 InvokerFactory::InvokerFactory() {}
33 
~InvokerFactory()34 InvokerFactory::~InvokerFactory()
35 {
36     isAvailable_ = false;
37     creators_.clear();
38 }
39 
Get()40 InvokerFactory &InvokerFactory::Get()
41 {
42     static InvokerFactory instance;
43     return instance;
44 }
45 
Register(int protocol,InvokerCreator creator)46 bool InvokerFactory::Register(int protocol, InvokerCreator creator)
47 {
48     if (isAvailable_ != true) {
49         return false;
50     }
51     std::lock_guard<std::mutex> lockGuard(factoryMutex_);
52 
53     /* check isAvailable_ == true again when a thread take mutex */
54     if (isAvailable_ != true) {
55         return false;
56     }
57     return creators_.insert(std::make_pair(protocol, creator)).second;
58 }
59 
Unregister(int protocol)60 void InvokerFactory::Unregister(int protocol)
61 {
62     if (isAvailable_ != true) {
63         return;
64     }
65     std::lock_guard<std::mutex> lockGuard(factoryMutex_);
66 
67     /* check isAvailable_ == true again when a thread take mutex */
68     if (isAvailable_ != true) {
69         return;
70     }
71     (void)creators_.erase(protocol);
72 }
73 
newInstance(int protocol)74 IRemoteInvoker *InvokerFactory::newInstance(int protocol)
75 {
76     if (isAvailable_ != true) {
77         return nullptr;
78     }
79     std::lock_guard<std::mutex> lockGuard(factoryMutex_);
80 
81     /* check isAvailable_ == true again when a thread take mutex */
82     if (isAvailable_ != true) {
83         return nullptr;
84     }
85     auto it = creators_.find(protocol);
86     if (it != creators_.end() && (it->second != nullptr)) {
87         return it->second();
88     }
89     return nullptr;
90 }
91 #ifdef CONFIG_IPC_SINGLE
92 } // namespace IPC_SINGLE
93 #endif
94 } // namespace OHOS