OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #ifndef MOJO_APPLICATION_APP_LIFETIME_HELPER_H_ |
| 6 #define MOJO_APPLICATION_APP_LIFETIME_HELPER_H_ |
| 7 |
| 8 #include "base/basictypes.h" |
| 9 #include "base/memory/scoped_ptr.h" |
| 10 #include "base/single_thread_task_runner.h" |
| 11 |
| 12 namespace mojo { |
| 13 |
| 14 class AppLifetimeHelper; |
| 15 |
| 16 // A service implementation should keep this object as a member variable to hold |
| 17 // a reference on the application. |
| 18 // Since services can live on different threads than the app, this class is |
| 19 // safe to use on any thread. However, each instance should only be used on one |
| 20 // thread at a time (otherwise there'll be races between the addref resulting |
| 21 // from cloning and destruction). |
| 22 class AppRefCount { |
| 23 public: |
| 24 ~AppRefCount(); |
| 25 |
| 26 // When a service creates another object that is held by the client, it should |
| 27 // also vend to it a refcount using this method. That way if the caller stops |
| 28 // holding on to the service but keeps the reference to the object, the app is |
| 29 // still alive. |
| 30 scoped_ptr<AppRefCount> Clone(); |
| 31 |
| 32 private: |
| 33 friend AppLifetimeHelper; |
| 34 |
| 35 AppRefCount(AppLifetimeHelper* app_lifetime_helper, |
| 36 scoped_refptr<base::SingleThreadTaskRunner> app_task_runner); |
| 37 |
| 38 // Don't need to use weak ptr because if the app thread is alive that means |
| 39 // app is. |
| 40 AppLifetimeHelper* app_lifetime_helper_; |
| 41 scoped_refptr<base::SingleThreadTaskRunner> app_task_runner_; |
| 42 |
| 43 #ifndef NDEBUG |
| 44 scoped_refptr<base::SingleThreadTaskRunner> clone_task_runner_; |
| 45 #endif |
| 46 |
| 47 DISALLOW_COPY_AND_ASSIGN(AppRefCount); |
| 48 }; |
| 49 |
| 50 // This is a helper class for apps to manage their lifetime, specifically so |
| 51 // apps can quit when they're not used anymore. |
| 52 // An app can contain an object of this class as a member variable. Each time it |
| 53 // creates an instance of a service, it gives it a refcount using |
| 54 // CreateAppRefCount. The service implementation then keeps that object as a |
| 55 // member variable. When all the service implemenations go away, the app will be |
| 56 // quit with a call to mojo::ApplicationImpl::Terminate(). |
| 57 class AppLifetimeHelper { |
| 58 public: |
| 59 AppLifetimeHelper(); |
| 60 ~AppLifetimeHelper(); |
| 61 |
| 62 scoped_ptr<AppRefCount> CreateAppRefCount(); |
| 63 |
| 64 private: |
| 65 friend AppRefCount; |
| 66 void AddRef(); |
| 67 void Release(); |
| 68 |
| 69 int ref_count_; |
| 70 |
| 71 DISALLOW_COPY_AND_ASSIGN(AppLifetimeHelper); |
| 72 }; |
| 73 |
| 74 } // namespace mojo |
| 75 |
| 76 #endif // MOJO_APPLICATION_APP_LIFETIME_HELPER_H_ |
OLD | NEW |