skia2/include/utils/SkThreadPool.h
commit-bot@chromium.org 6ee68583f8 SkThreadPool: allow for Runnables that add other Runnables to the pool.
There's a scenario that we're currently not allowing for, but I'd really like to use in DM:

1) client calls add(SomeRunnable*) several times
2) client calls wait()
3) any of the runnables added by the client _themselves_ call add(SomeOtherRunnable*)
4-inf) maybe those SomeOtherRunnables too call add(SomeCrazyThirdRunnable*), etc.

Right now in this scenario we'll assert in debug mode in step 3) when we call
add() and we're waiting to stop, and do strange unspecified things in release
mode.

The old threadpool had basically two states: running, and waiting to stop.  If
a thread saw we were waiting to stop and the queue was empty, that thread shut
down.  This wasn't accounting for any work that other threads might be doing;
potentially they were about to add to the queue.

So now we have three states: running, waiting, and halting.  When the client
calls wait() (or the destructor triggers), we move into waiting.  When a thread
notices we're _really_ done, that is, have an empty queue and there are no
active threads, we move into halting.  The halting state actually triggers the
threads to stop, which wait() is patiently join()ing on.

BUG=
R=bungeman@google.com, bsalomon@google.com

Author: mtklein@google.com

Review URL: https://codereview.chromium.org/26389005

git-svn-id: http://skia.googlecode.com/svn/trunk@11852 2bbb7eff-a529-9590-31e7-b0007b416f81
2013-10-18 14:19:19 +00:00

64 lines
1.7 KiB
C++

/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkThreadPool_DEFINED
#define SkThreadPool_DEFINED
#include "SkCondVar.h"
#include "SkRunnable.h"
#include "SkTDArray.h"
#include "SkTInternalLList.h"
class SkThread;
class SkThreadPool {
public:
/**
* Create a threadpool with count threads, or one thread per core if kThreadPerCore.
*/
static const int kThreadPerCore = -1;
explicit SkThreadPool(int count);
~SkThreadPool();
/**
* Queues up an SkRunnable to run when a thread is available, or immediately if
* count is 0. NULL is a safe no-op. Does not take ownership.
*/
void add(SkRunnable*);
/**
* Block until all added SkRunnables have completed. Once called, calling add() is undefined.
*/
void wait();
private:
struct LinkedRunnable {
// Unowned pointer.
SkRunnable* fRunnable;
private:
SK_DECLARE_INTERNAL_LLIST_INTERFACE(LinkedRunnable);
};
enum State {
kRunning_State, // Normal case. We've been constructed and no one has called wait().
kWaiting_State, // wait has been called, but there still might be work to do or being done.
kHalting_State, // There's no work to do and no thread is busy. All threads can shut down.
};
SkTInternalLList<LinkedRunnable> fQueue;
SkCondVar fReady;
SkTDArray<SkThread*> fThreads;
State fState;
int fBusyThreads;
static void Loop(void*); // Static because we pass in this.
};
#endif