@@ -200,17 +200,31 @@ std::shared_ptr<ov::Model> Plugin::clone_and_transform_model(const std::shared_p
200200 return cloned_model;
201201}
202202
203- std::map<std::string, RemoteContextImpl::Ptr> Plugin::get_default_contexts () const {
204- static std::map<std::string, std::shared_ptr<RemoteContextImpl>> m_default_contexts;
205- static std::once_flag m_default_contexts_once;
203+ // weak map to hold singleton default contexts
204+ // Weak singleton map is used to share contexts between multiple plugin(or Core) instances.
205+ // It is needed to ensure that context is released before plugin is unloaded.
206+ // As the actual ownership is in plugin class, the ownership is released when plugin is destructed.
207+ std::map<std::string, std::weak_ptr<RemoteContextImpl>> weak_singleton_default_contexts;
208+ std::mutex singleton_default_contexts_mutex;
206209
210+ std::map<std::string, RemoteContextImpl::Ptr> Plugin::get_default_contexts () const {
207211 std::call_once (m_default_contexts_once, [this ]() {
208- // Create default context
212+ std::lock_guard<std::mutex> lock (singleton_default_contexts_mutex);
209213 for (auto & device : m_device_map) {
210214 const auto device_name = get_device_name () + " ." + device.first ;
215+
216+ // If already initialized, use existing one
217+ if (weak_singleton_default_contexts.find (device.first ) != weak_singleton_default_contexts.end ()) {
218+ if (auto ctx = weak_singleton_default_contexts[device.first ].lock ()) {
219+ m_default_contexts[device.first ] = ctx;
220+ continue ;
221+ }
222+ }
223+ // If context is not created yet or expired, create new one
211224 const auto initialize = false ;
212225 auto ctx = std::make_shared<RemoteContextImpl>(device_name, std::vector<cldnn::device::ptr>{device.second }, initialize);
213- m_default_contexts.insert ({device.first , ctx});
226+ weak_singleton_default_contexts[device.first ] = ctx;
227+ m_default_contexts[device.first ] = ctx;
214228 }
215229 });
216230 return m_default_contexts;
@@ -972,6 +986,10 @@ uint32_t Plugin::get_optimal_batch_size(const ov::AnyMap& options) const {
972986
973987 return batch;
974988}
989+ void Plugin::cleanup () {
990+ GPU_DEBUG_INFO << " [GPU] Plugin shutdown" << std::endl;
991+ m_default_contexts.clear ();
992+ }
975993
976994} // namespace ov::intel_gpu
977995
0 commit comments