blob: 0aa7c08ad53b6e48d8f82ce61b95dca36fdc679e [file] [log] [blame]
scroggo@google.com4177ef42012-10-31 15:52:16 +00001/*
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"
commit-bot@chromium.orga7538ba2013-10-10 18:49:04 +000012#include "SkRunnable.h"
scroggo@google.com4177ef42012-10-31 15:52:16 +000013#include "SkTDArray.h"
bsalomon@google.com42619d82012-12-03 14:54:59 +000014#include "SkTInternalLList.h"
scroggo@google.com4177ef42012-10-31 15:52:16 +000015
scroggo@google.com4177ef42012-10-31 15:52:16 +000016class SkThread;
17
18class SkThreadPool {
19
20public:
21 /**
commit-bot@chromium.org44c661f2013-04-22 15:23:14 +000022 * Create a threadpool with count threads, or one thread per core if kThreadPerCore.
scroggo@google.com4177ef42012-10-31 15:52:16 +000023 */
commit-bot@chromium.org44c661f2013-04-22 15:23:14 +000024 static const int kThreadPerCore = -1;
scroggo@google.com4177ef42012-10-31 15:52:16 +000025 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
commit-bot@chromium.orga7538ba2013-10-10 18:49:04 +000034 /**
35 * Block until all added SkRunnables have completed. Once called, calling add() is undefined.
36 */
37 void wait();
38
scroggo@google.com4177ef42012-10-31 15:52:16 +000039 private:
40 struct LinkedRunnable {
41 // Unowned pointer.
42 SkRunnable* fRunnable;
43
44 private:
bsalomon@google.com42619d82012-12-03 14:54:59 +000045 SK_DECLARE_INTERNAL_LLIST_INTERFACE(LinkedRunnable);
scroggo@google.com4177ef42012-10-31 15:52:16 +000046 };
47
commit-bot@chromium.org6ee68582013-10-18 14:19:19 +000048 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;
scroggo@google.com4177ef42012-10-31 15:52:16 +000059
60 static void Loop(void*); // Static because we pass in this.
61};
62
63#endif