1 // 2 // 3 // Copyright 2018 gRPC authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // 17 // 18 19 #include "src/core/client_channel/global_subchannel_pool.h" 20 21 #include <grpc/support/port_platform.h> 22 23 #include <utility> 24 25 #include "src/core/client_channel/subchannel.h" 26 27 namespace grpc_core { 28 instance()29RefCountedPtr<GlobalSubchannelPool> GlobalSubchannelPool::instance() { 30 static GlobalSubchannelPool* p = new GlobalSubchannelPool(); 31 return p->RefAsSubclass<GlobalSubchannelPool>(); 32 } 33 RegisterSubchannel(const SubchannelKey & key,RefCountedPtr<Subchannel> constructed)34RefCountedPtr<Subchannel> GlobalSubchannelPool::RegisterSubchannel( 35 const SubchannelKey& key, RefCountedPtr<Subchannel> constructed) { 36 MutexLock lock(&mu_); 37 auto it = subchannel_map_.find(key); 38 if (it != subchannel_map_.end()) { 39 RefCountedPtr<Subchannel> existing = it->second->RefIfNonZero(); 40 if (existing != nullptr) return existing; 41 } 42 subchannel_map_[key] = constructed.get(); 43 return constructed; 44 } 45 UnregisterSubchannel(const SubchannelKey & key,Subchannel * subchannel)46void GlobalSubchannelPool::UnregisterSubchannel(const SubchannelKey& key, 47 Subchannel* subchannel) { 48 MutexLock lock(&mu_); 49 auto it = subchannel_map_.find(key); 50 // delete only if key hasn't been re-registered to a different subchannel 51 // between strong-unreffing and unregistration of subchannel. 52 if (it != subchannel_map_.end() && it->second == subchannel) { 53 subchannel_map_.erase(it); 54 } 55 } 56 FindSubchannel(const SubchannelKey & key)57RefCountedPtr<Subchannel> GlobalSubchannelPool::FindSubchannel( 58 const SubchannelKey& key) { 59 MutexLock lock(&mu_); 60 auto it = subchannel_map_.find(key); 61 if (it == subchannel_map_.end()) return nullptr; 62 return it->second->RefIfNonZero(); 63 } 64 65 } // namespace grpc_core 66