• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef WEBRTC_BASE_WORKER_H_
12 #define WEBRTC_BASE_WORKER_H_
13 
14 #include "webrtc/base/constructormagic.h"
15 #include "webrtc/base/messagehandler.h"
16 
17 namespace rtc {
18 
19 class Thread;
20 
21 // A worker is an object that performs some specific long-lived task in an
22 // event-driven manner.
23 // The only method that should be considered thread-safe is HaveWork(), which
24 // allows you to signal the availability of work from any thread. All other
25 // methods are thread-hostile. Specifically:
26 // StartWork()/StopWork() should not be called concurrently with themselves or
27 // each other, and it is an error to call them while the worker is running on
28 // a different thread.
29 // The destructor may not be called if the worker is currently running
30 // (regardless of the thread), but you can call StopWork() in a subclass's
31 // destructor.
32 class Worker : private MessageHandler {
33  public:
34   Worker();
35 
36   // Destroys this Worker, but it must have already been stopped via StopWork().
37   ~Worker() override;
38 
39   // Attaches the worker to the current thread and begins processing work if not
40   // already doing so.
41   bool StartWork();
42   // Stops processing work if currently doing so and detaches from the current
43   // thread.
44   bool StopWork();
45 
46  protected:
47   // Signal that work is available to be done. May only be called within the
48   // lifetime of a OnStart()/OnStop() pair.
49   void HaveWork();
50 
51   // These must be implemented by a subclass.
52   // Called on the worker thread to start working.
53   virtual void OnStart() = 0;
54   // Called on the worker thread when work has been signalled via HaveWork().
55   virtual void OnHaveWork() = 0;
56   // Called on the worker thread to stop working. Upon return, any pending
57   // OnHaveWork() calls are cancelled.
58   virtual void OnStop() = 0;
59 
60  private:
61   // Inherited from MessageHandler.
62   void OnMessage(Message* msg) override;
63 
64   // The thread that is currently doing the work.
65   Thread *worker_thread_;
66 
67   RTC_DISALLOW_COPY_AND_ASSIGN(Worker);
68 };
69 
70 }  // namespace rtc
71 
72 #endif  // WEBRTC_BASE_WORKER_H_
73