Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright 2012 Google Inc.
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #ifndef SkThreadPool_DEFINED
      9 #define SkThreadPool_DEFINED
     10 
     11 #include "SkCondVar.h"
     12 #include "SkRunnable.h"
     13 #include "SkTDArray.h"
     14 #include "SkTInternalLList.h"
     15 
     16 class SkThread;
     17 
     18 class SkThreadPool {
     19 
     20 public:
     21     /**
     22      * Create a threadpool with count threads, or one thread per core if kThreadPerCore.
     23      */
     24     static const int kThreadPerCore = -1;
     25     explicit SkThreadPool(int count);
     26     ~SkThreadPool();
     27 
     28     /**
     29      * Queues up an SkRunnable to run when a thread is available, or immediately if
     30      * count is 0.  NULL is a safe no-op.  Does not take ownership.
     31      */
     32     void add(SkRunnable*);
     33 
     34     /**
     35      * Block until all added SkRunnables have completed.  Once called, calling add() is undefined.
     36      */
     37     void wait();
     38 
     39  private:
     40     struct LinkedRunnable {
     41         // Unowned pointer.
     42         SkRunnable* fRunnable;
     43 
     44     private:
     45         SK_DECLARE_INTERNAL_LLIST_INTERFACE(LinkedRunnable);
     46     };
     47 
     48     enum State {
     49         kRunning_State,  // Normal case.  We've been constructed and no one has called wait().
     50         kWaiting_State,  // wait has been called, but there still might be work to do or being done.
     51         kHalting_State,  // There's no work to do and no thread is busy.  All threads can shut down.
     52     };
     53 
     54     SkTInternalLList<LinkedRunnable> fQueue;
     55     SkCondVar                        fReady;
     56     SkTDArray<SkThread*>             fThreads;
     57     State                            fState;
     58     int                              fBusyThreads;
     59 
     60     static void Loop(void*);  // Static because we pass in this.
     61 };
     62 
     63 #endif
     64