1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
6 
7 #ifndef BASE_THREAD_H_
8 #define BASE_THREAD_H_
9 
10 #include <stdint.h>
11 #include <string>
12 
13 #include "base/message_loop.h"
14 #include "base/platform_thread.h"
15 
16 namespace base {
17 
18 // A simple thread abstraction that establishes a MessageLoop on a new thread.
19 // The consumer uses the MessageLoop of the thread to cause code to execute on
20 // the thread.  When this object is destroyed the thread is terminated.  All
21 // pending tasks queued on the thread's message loop will run to completion
22 // before the thread is terminated.
23 class Thread : PlatformThread::Delegate {
24  public:
25   struct Options {
26     // Specifies the type of message loop that will be allocated on the thread.
27     MessageLoop::Type message_loop_type;
28 
29     // Specifies the maximum stack size that the thread is allowed to use.
30     // This does not necessarily correspond to the thread's initial stack size.
31     // A value of 0 indicates that the default maximum should be used.
32     size_t stack_size;
33 
34     // Specifies the transient and permanent hang timeouts for background hang
35     // monitoring. A value of 0 indicates there is no timeout.
36     uint32_t transient_hang_timeout;
37     uint32_t permanent_hang_timeout;
38 
OptionsOptions39     Options()
40         : message_loop_type(MessageLoop::TYPE_DEFAULT),
41           stack_size(0),
42           transient_hang_timeout(0),
43           permanent_hang_timeout(0) {}
OptionsOptions44     Options(MessageLoop::Type type, size_t size)
45         : message_loop_type(type),
46           stack_size(size),
47           transient_hang_timeout(0),
48           permanent_hang_timeout(0) {}
49   };
50 
51   // Constructor.
52   // name is a display string to identify the thread.
53   explicit Thread(const char* name);
54 
55   // Destroys the thread, stopping it if necessary.
56   //
57   // NOTE: If you are subclassing from Thread, and you wish for your CleanUp
58   // method to be called, then you need to call Stop() from your destructor.
59   //
60   virtual ~Thread();
61 
62   // Starts the thread.  Returns true if the thread was successfully started;
63   // otherwise, returns false.  Upon successful return, the message_loop()
64   // getter will return non-null.
65   //
66   // Note: This function can't be called on Windows with the loader lock held;
67   // i.e. during a DllMain, global object construction or destruction, atexit()
68   // callback.
69   bool Start();
70 
71   // Starts the thread. Behaves exactly like Start in addition to allow to
72   // override the default options.
73   //
74   // Note: This function can't be called on Windows with the loader lock held;
75   // i.e. during a DllMain, global object construction or destruction, atexit()
76   // callback.
77   bool StartWithOptions(const Options& options);
78 
79   // Signals the thread to exit and returns once the thread has exited.  After
80   // this method returns, the Thread object is completely reset and may be used
81   // as if it were newly constructed (i.e., Start may be called again).
82   //
83   // Stop may be called multiple times and is simply ignored if the thread is
84   // already stopped.
85   //
86   // NOTE: This method is optional.  It is not strictly necessary to call this
87   // method as the Thread's destructor will take care of stopping the thread if
88   // necessary.
89   //
90   void Stop();
91 
92   // Signals the thread to exit in the near future.
93   //
94   // WARNING: This function is not meant to be commonly used. Use at your own
95   // risk. Calling this function will cause message_loop() to become invalid in
96   // the near future. This function was created to workaround a specific
97   // deadlock on Windows with printer worker thread. In any other case, Stop()
98   // should be used.
99   //
100   // StopSoon should not be called multiple times as it is risky to do so. It
101   // could cause a timing issue in message_loop() access. Call Stop() to reset
102   // the thread object once it is known that the thread has quit.
103   void StopSoon();
104 
105   // Returns the message loop for this thread.  Use the MessageLoop's
106   // PostTask methods to execute code on the thread.  This only returns
107   // non-null after a successful call to Start.  After Stop has been called,
108   // this will return NULL.
109   //
110   // NOTE: You must not call this MessageLoop's Quit method directly.  Use
111   // the Thread's Stop method instead.
112   //
message_loop()113   MessageLoop* message_loop() const { return message_loop_; }
114 
115   // Set the name of this thread (for display in debugger too).
thread_name()116   const std::string& thread_name() { return name_; }
117 
118   // The native thread handle.
thread_handle()119   PlatformThreadHandle thread_handle() { return thread_; }
120 
121   // The thread ID.
thread_id()122   PlatformThreadId thread_id() const { return thread_id_; }
123 
124   // Reset thread ID as current thread.
reset_thread_id()125   PlatformThreadId reset_thread_id() {
126     thread_id_ = PlatformThread::CurrentId();
127     return thread_id_;
128   }
129 
130   // Returns true if the thread has been started, and not yet stopped.
131   // When a thread is running, the thread_id_ is non-zero.
IsRunning()132   bool IsRunning() const { return thread_id_ != 0; }
133 
134  protected:
135   // Called just prior to starting the message loop
Init()136   virtual void Init() {}
137 
138   // Called just after the message loop ends
CleanUp()139   virtual void CleanUp() {}
140 
141   static void SetThreadWasQuitProperly(bool flag);
142   static bool GetThreadWasQuitProperly();
143 
144  private:
145   // PlatformThread::Delegate methods:
146   virtual void ThreadMain() override;
147 
148   // We piggy-back on the startup_data_ member to know if we successfully
149   // started the thread.  This way we know that we need to call Join.
thread_was_started()150   bool thread_was_started() const { return startup_data_ != NULL; }
151 
152   // Used to pass data to ThreadMain.
153   struct StartupData;
154   StartupData* startup_data_;
155 
156   // The thread's handle.
157   PlatformThreadHandle thread_;
158 
159   // The thread's message loop.  Valid only while the thread is alive.  Set
160   // by the created thread.
161   MessageLoop* message_loop_;
162 
163   // Our thread's ID.
164   PlatformThreadId thread_id_;
165 
166   // The name of the thread.  Used for debugging purposes.
167   std::string name_;
168 
169   friend class ThreadQuitTask;
170 
171   DISALLOW_COPY_AND_ASSIGN(Thread);
172 };
173 
174 }  // namespace base
175 
176 #endif  // BASE_THREAD_H_
177