1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2015 Realm Inc.
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 ////////////////////////////////////////////////////////////////////////////
19 #ifndef REALM_WEAK_REALM_NOTIFIER_HPP
20 #define REALM_WEAK_REALM_NOTIFIER_HPP
22 #include "execution_context_id.hpp"
31 template<typename> class EventLoopSignal;
35 // WeakRealmNotifier stores a weak reference to a Realm instance, along with all of
36 // the information about a Realm that needs to be accessed from other threads.
37 // This is needed to avoid forming strong references to the Realm instances on
38 // other threads, which can produce deadlocks when the last strong reference to
39 // a Realm instance is released from within a function holding the cache lock.
40 class WeakRealmNotifier {
42 WeakRealmNotifier(const std::shared_ptr<Realm>& realm, bool cache);
45 // Get a strong reference to the cached realm
46 std::shared_ptr<Realm> realm() const { return m_realm.lock(); }
48 // Does this WeakRealmNotifier store a Realm instance that should be used on the current thread?
49 bool is_cached_for_execution_context(const AnyExecutionContextID& execution_context) const
51 return m_cache && m_execution_context == execution_context;
54 // Has the Realm instance been destroyed?
55 bool expired() const { return m_realm.expired(); }
57 // Is this a WeakRealmNotifier for the given Realm instance?
58 bool is_for_realm(Realm* realm) const { return realm == m_realm_key; }
63 std::weak_ptr<Realm> m_realm;
64 AnyExecutionContextID m_execution_context;
69 const std::weak_ptr<Realm> weak_realm;
70 void operator()() const;
72 std::shared_ptr<util::EventLoopSignal<Callback>> m_signal;
78 #endif // REALM_WEAK_REALM_NOTIFIER_HPP