blob: 46dd0a3bad5302db758f2761a7db90def28ccae0 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004--2009, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
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.
15 *
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.
26 */
27
28#ifndef TALK_BASE_SIGNALTHREAD_H_
29#define TALK_BASE_SIGNALTHREAD_H_
30
31#include <string>
32
33#include "talk/base/constructormagic.h"
34#include "talk/base/sigslot.h"
35#include "talk/base/thread.h"
36
37namespace talk_base {
38
39///////////////////////////////////////////////////////////////////////////////
40// SignalThread - Base class for worker threads. The main thread should call
41// Start() to begin work, and then follow one of these models:
42// Normal: Wait for SignalWorkDone, and then call Release to destroy.
43// Cancellation: Call Release(true), to abort the worker thread.
44// Fire-and-forget: Call Release(false), which allows the thread to run to
45// completion, and then self-destruct without further notification.
46// Periodic tasks: Wait for SignalWorkDone, then eventually call Start()
47// again to repeat the task. When the instance isn't needed anymore,
48// call Release. DoWork, OnWorkStart and OnWorkStop are called again,
49// on a new thread.
50// The subclass should override DoWork() to perform the background task. By
51// periodically calling ContinueWork(), it can check for cancellation.
52// OnWorkStart and OnWorkDone can be overridden to do pre- or post-work
53// tasks in the context of the main thread.
54///////////////////////////////////////////////////////////////////////////////
55
56class SignalThread
57 : public sigslot::has_slots<>,
58 protected MessageHandler {
59 public:
60 SignalThread();
61
62 // Context: Main Thread. Call before Start to change the worker's name.
63 bool SetName(const std::string& name, const void* obj);
64
65 // Context: Main Thread. Call before Start to change the worker's priority.
66 bool SetPriority(ThreadPriority priority);
67
68 // Context: Main Thread. Call to begin the worker thread.
69 void Start();
70
71 // Context: Main Thread. If the worker thread is not running, deletes the
72 // object immediately. Otherwise, asks the worker thread to abort processing,
73 // and schedules the object to be deleted once the worker exits.
74 // SignalWorkDone will not be signalled. If wait is true, does not return
75 // until the thread is deleted.
76 void Destroy(bool wait);
77
78 // Context: Main Thread. If the worker thread is complete, deletes the
79 // object immediately. Otherwise, schedules the object to be deleted once
80 // the worker thread completes. SignalWorkDone will be signalled.
81 void Release();
82
83 // Context: Main Thread. Signalled when work is complete.
84 sigslot::signal1<SignalThread *> SignalWorkDone;
85
86 enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE };
87
88 protected:
89 virtual ~SignalThread();
90
91 Thread* worker() { return &worker_; }
92
93 // Context: Main Thread. Subclass should override to do pre-work setup.
94 virtual void OnWorkStart() { }
95
96 // Context: Worker Thread. Subclass should override to do work.
97 virtual void DoWork() = 0;
98
99 // Context: Worker Thread. Subclass should call periodically to
100 // dispatch messages and determine if the thread should terminate.
101 bool ContinueWork();
102
103 // Context: Worker Thread. Subclass should override when extra work is
104 // needed to abort the worker thread.
105 virtual void OnWorkStop() { }
106
107 // Context: Main Thread. Subclass should override to do post-work cleanup.
108 virtual void OnWorkDone() { }
109
110 // Context: Any Thread. If subclass overrides, be sure to call the base
111 // implementation. Do not use (message_id < ST_MSG_FIRST_AVAILABLE)
112 virtual void OnMessage(Message *msg);
113
114 private:
115 enum State {
116 kInit, // Initialized, but not started
117 kRunning, // Started and doing work
118 kReleasing, // Same as running, but to be deleted when work is done
119 kComplete, // Work is done
120 kStopping, // Work is being interrupted
121 };
122
123 class Worker : public Thread {
124 public:
125 explicit Worker(SignalThread* parent) : parent_(parent) {}
wu@webrtc.org3c5d2b42013-10-18 16:27:26 +0000126 virtual ~Worker() { Stop(); }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127 virtual void Run() { parent_->Run(); }
128
129 private:
130 SignalThread* parent_;
131
132 DISALLOW_IMPLICIT_CONSTRUCTORS(Worker);
133 };
134
wjia@webrtc.orgdd82fa72014-02-10 23:20:15 +0000135 class EnterExit {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136 public:
wjia@webrtc.orgdd82fa72014-02-10 23:20:15 +0000137 explicit EnterExit(SignalThread* t) : t_(t) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138 t_->cs_.Enter();
139 // If refcount_ is zero then the object has already been deleted and we
140 // will be double-deleting it in ~EnterExit()! (shouldn't happen)
141 ASSERT(t_->refcount_ != 0);
142 ++t_->refcount_;
143 }
wjia@webrtc.orgdd82fa72014-02-10 23:20:15 +0000144 ~EnterExit() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145 bool d = (0 == --t_->refcount_);
146 t_->cs_.Leave();
147 if (d)
148 delete t_;
149 }
150
151 private:
152 SignalThread* t_;
153
154 DISALLOW_IMPLICIT_CONSTRUCTORS(EnterExit);
155 };
156
157 void Run();
158 void OnMainThreadDestroyed();
159
160 Thread* main_;
161 Worker worker_;
162 CriticalSection cs_;
163 State state_;
164 int refcount_;
165
166 DISALLOW_COPY_AND_ASSIGN(SignalThread);
167};
168
169///////////////////////////////////////////////////////////////////////////////
170
171} // namespace talk_base
172
173#endif // TALK_BASE_SIGNALTHREAD_H_