3 * Copyright 2004 Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #ifndef TALK_BASE_THREAD_H_
29 #define TALK_BASE_THREAD_H_
39 #include "talk/base/constructormagic.h"
40 #include "talk/base/messagequeue.h"
43 #include "talk/base/win32.h"
55 static ThreadManager* Instance();
57 Thread* CurrentThread();
58 void SetCurrentThread(Thread* thread);
60 // Returns a thread object with its thread_ ivar set
61 // to whatever the OS uses to represent the thread.
62 // If there already *is* a Thread object corresponding to this thread,
63 // this method will return that. Otherwise it creates a new Thread
64 // object whose wrapped() method will return true, and whose
65 // handle will, on Win32, be opened with only synchronization privileges -
66 // if you need more privilegs, rather than changing this method, please
67 // write additional code to adjust the privileges, or call a different
68 // factory method of your own devising, because this one gets used in
69 // unexpected contexts (like inside browser plugins) and it would be a
70 // shame to break it. It is also conceivable on Win32 that we won't even
71 // be able to get synchronization privileges, in which case the result
72 // will have a NULL handle.
73 Thread *WrapCurrentThread();
74 void UnwrapCurrentThread();
85 DISALLOW_COPY_AND_ASSIGN(ThreadManager);
98 PRIORITY_ABOVE_NORMAL = 1,
104 virtual ~Runnable() {}
105 virtual void Run(Thread* thread) = 0;
111 DISALLOW_COPY_AND_ASSIGN(Runnable);
114 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
116 class Thread : public MessageQueue {
118 explicit Thread(SocketServer* ss = NULL);
119 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
120 // guarantee Stop() is explicitly called before the subclass is destroyed).
121 // This is required to avoid a data race between the destructor modifying the
122 // vtable, and the Thread::PreRun calling the virtual method Run().
125 static Thread* Current();
127 bool IsCurrent() const {
128 return Current() == this;
131 // Sleeps the calling thread for the specified number of milliseconds, during
132 // which time no processing is performed. Returns false if sleeping was
133 // interrupted by a signal (POSIX only).
134 static bool SleepMs(int millis);
136 // Sets the thread's name, for debugging. Must be called before Start().
137 // If |obj| is non-NULL, its value is appended to |name|.
138 const std::string& name() const { return name_; }
139 bool SetName(const std::string& name, const void* obj);
141 // Sets the thread's priority. Must be called before Start().
142 ThreadPriority priority() const { return priority_; }
143 bool SetPriority(ThreadPriority priority);
145 // Starts the execution of the thread.
146 bool started() const { return started_; }
147 bool Start(Runnable* runnable = NULL);
149 // Used for fire-and-forget threads. Deletes this thread object when the
150 // Run method returns.
152 delete_self_when_complete_ = true;
155 // Tells the thread to stop and waits until it is joined.
156 // Never call Stop on the current thread. Instead use the inherited Quit
157 // function which will exit the base MessageQueue without terminating the
158 // underlying OS thread.
161 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
162 // work, override Run(). To receive and dispatch messages, call
163 // ProcessMessages occasionally.
166 virtual void Send(MessageHandler *phandler, uint32 id = 0,
167 MessageData *pdata = NULL);
169 // Convenience method to invoke a functor on another thread. Caller must
170 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
171 // Uses Send() internally, which blocks the current thread until execution
173 // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
174 template <class ReturnT, class FunctorT>
175 ReturnT Invoke(const FunctorT& functor) {
176 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
178 return handler.result();
182 virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
183 MessageList* removed = NULL);
184 virtual void ReceiveSends();
186 // ProcessMessages will process I/O and dispatch messages until:
187 // 1) cms milliseconds have elapsed (returns true)
188 // 2) Stop() is called (returns false)
189 bool ProcessMessages(int cms);
191 // Returns true if this is a thread that we created using the standard
192 // constructor, false if it was created by a call to
193 // ThreadManager::WrapCurrentThread(). The main thread of an application
194 // is generally not owned, since the OS representation of the thread
195 // obviously exists before we can get to it.
196 // You cannot call Start on non-owned threads.
200 HANDLE GetHandle() const {
203 DWORD GetId() const {
207 pthread_t GetPThread() {
212 // This method should be called when thread is created using non standard
213 // method, like derived implementation of talk_base::Thread and it can not be
214 // started by calling Start(). This will set started flag to true and
215 // owned to false. This must be called from the current thread.
216 // NOTE: These methods should be used by the derived classes only, added here
219 void UnwrapCurrent();
222 // Blocks the calling thread until this thread has terminated.
226 static void *PreRun(void *pv);
228 // ThreadManager calls this instead WrapCurrent() because
229 // ThreadManager::Instance() cannot be used while ThreadManager is
231 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager);
233 std::list<_SendMessage> sendlist_;
235 ThreadPriority priority_;
248 bool delete_self_when_complete_;
250 friend class ThreadManager;
252 DISALLOW_COPY_AND_ASSIGN(Thread);
255 // AutoThread automatically installs itself at construction
256 // uninstalls at destruction, if a Thread object is
257 // _not already_ associated with the current OS thread.
259 class AutoThread : public Thread {
261 explicit AutoThread(SocketServer* ss = 0);
262 virtual ~AutoThread();
265 DISALLOW_COPY_AND_ASSIGN(AutoThread);
268 // Win32 extension for threads that need to use COM
270 class ComThread : public Thread {
273 virtual ~ComThread() { Stop(); }
279 DISALLOW_COPY_AND_ASSIGN(ComThread);
283 // Provides an easy way to install/uninstall a socketserver on a thread.
284 class SocketServerScope {
286 explicit SocketServerScope(SocketServer* ss) {
287 old_ss_ = Thread::Current()->socketserver();
288 Thread::Current()->set_socketserver(ss);
290 ~SocketServerScope() {
291 Thread::Current()->set_socketserver(old_ss_);
295 SocketServer* old_ss_;
297 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
300 } // namespace talk_base
302 #endif // TALK_BASE_THREAD_H_