Home | History | Annotate | Download | only in base
      1 /*
      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/thread.h"
     34 #include "talk/base/sigslot.h"
     35 
     36 namespace talk_base {
     37 
     38 ///////////////////////////////////////////////////////////////////////////////
     39 // SignalThread - Base class for worker threads.  The main thread should call
     40 //  Start() to begin work, and then follow one of these models:
     41 //   Normal: Wait for SignalWorkDone, and then call Release to destroy.
     42 //   Cancellation: Call Release(true), to abort the worker thread.
     43 //   Fire-and-forget: Call Release(false), which allows the thread to run to
     44 //    completion, and then self-destruct without further notification.
     45 //   Periodic tasks: Wait for SignalWorkDone, then eventually call Start()
     46 //    again to repeat the task. When the instance isn't needed anymore,
     47 //    call Release. DoWork, OnWorkStart and OnWorkStop are called again,
     48 //    on a new thread.
     49 //  The subclass should override DoWork() to perform the background task.  By
     50 //   periodically calling ContinueWork(), it can check for cancellation.
     51 //   OnWorkStart and OnWorkDone can be overridden to do pre- or post-work
     52 //   tasks in the context of the main thread.
     53 ///////////////////////////////////////////////////////////////////////////////
     54 
     55 class SignalThread : public sigslot::has_slots<>, protected MessageHandler {
     56  public:
     57   SignalThread();
     58 
     59   // Context: Main Thread.  Call before Start to change the worker's name.
     60   bool SetName(const std::string& name, const void* obj);
     61 
     62   // Context: Main Thread.  Call before Start to change the worker's priority.
     63   bool SetPriority(ThreadPriority priority);
     64 
     65   // Context: Main Thread.  Call to begin the worker thread.
     66   void Start();
     67 
     68   // Context: Main Thread.  If the worker thread is not running, deletes the
     69   // object immediately.  Otherwise, asks the worker thread to abort processing,
     70   // and schedules the object to be deleted once the worker exits.
     71   // SignalWorkDone will not be signalled.  If wait is true, does not return
     72   // until the thread is deleted.
     73   void Destroy(bool wait);
     74 
     75   // Context: Main Thread.  If the worker thread is complete, deletes the
     76   // object immediately.  Otherwise, schedules the object to be deleted once
     77   // the worker thread completes.  SignalWorkDone will be signalled.
     78   void Release();
     79 
     80   // Context: Main Thread.  Signalled when work is complete.
     81   sigslot::signal1<SignalThread *> SignalWorkDone;
     82 
     83   enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE };
     84 
     85  protected:
     86   virtual ~SignalThread();
     87 
     88   Thread* worker() { return &worker_; }
     89 
     90   // Context: Main Thread.  Subclass should override to do pre-work setup.
     91   virtual void OnWorkStart() { }
     92 
     93   // Context: Worker Thread.  Subclass should override to do work.
     94   virtual void DoWork() = 0;
     95 
     96   // Context: Worker Thread.  Subclass should call periodically to
     97   // dispatch messages and determine if the thread should terminate.
     98   bool ContinueWork();
     99 
    100   // Context: Worker Thread.  Subclass should override when extra work is
    101   // needed to abort the worker thread.
    102   virtual void OnWorkStop() { }
    103 
    104   // Context: Main Thread.  Subclass should override to do post-work cleanup.
    105   virtual void OnWorkDone() { }
    106 
    107   // Context: Any Thread.  If subclass overrides, be sure to call the base
    108   // implementation.  Do not use (message_id < ST_MSG_FIRST_AVAILABLE)
    109   virtual void OnMessage(Message *msg);
    110 
    111  private:
    112   enum State {
    113     kInit,            // Initialized, but not started
    114     kRunning,         // Started and doing work
    115     kReleasing,       // Same as running, but to be deleted when work is done
    116     kComplete,        // Work is done
    117     kStopping,        // Work is being interrupted
    118   };
    119 
    120   friend class Worker;
    121   class Worker : public Thread {
    122    public:
    123     SignalThread* parent_;
    124     virtual void Run() { parent_->Run(); }
    125   };
    126 
    127   friend class EnterExit;
    128   class EnterExit {
    129    public:
    130     explicit EnterExit(SignalThread* t) : t_(t) {
    131       t_->cs_.Enter();
    132       t_->refcount_ += 1;
    133     }
    134     ~EnterExit() {
    135       bool d = (0 == (--(t_->refcount_)));
    136       t_->cs_.Leave();
    137       if (d)
    138         delete t_;
    139     }
    140    private:
    141     SignalThread* t_;
    142   };
    143 
    144   void Run();
    145   void OnMainThreadDestroyed();
    146 
    147   Thread* main_;
    148   Worker worker_;
    149   CriticalSection cs_;
    150   State state_;
    151   int refcount_;
    152 };
    153 
    154 ///////////////////////////////////////////////////////////////////////////////
    155 
    156 }  // namespace talk_base
    157 
    158 #endif  // TALK_BASE_SIGNALTHREAD_H_
    159