| 1 |
/* |
| 2 |
* Copyright 2014 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 |
#include "src/core/SkTaskGroup.h" |
| 8 |
|
| 9 |
#include "include/core/SkExecutor.h" |
| 10 |
|
| 11 |
#include <type_traits> |
| 12 |
#include <utility> |
| 13 |
|
| 14 |
SkTaskGroup::SkTaskGroup(SkExecutor& executor) : fPending(0), fExecutor(executor) {} |
| 15 |
|
| 16 |
void SkTaskGroup::add(std::function<void(void)> fn) { |
| 17 |
this->add(std::move(fn), /* workList= */ 0); |
| 18 |
} |
| 19 |
|
| 20 |
void SkTaskGroup::add(std::function<void(void)> fn, int workList) { |
| 21 |
fPending.fetch_add(+1, std::memory_order_relaxed); |
| 22 |
fExecutor.add([this, fn{std::move(fn)}] { |
| 23 |
fn(); |
| 24 |
fPending.fetch_add(-1, std::memory_order_release); |
| 25 |
}, |
| 26 |
workList); |
| 27 |
} |
| 28 |
|
| 29 |
void SkTaskGroup::discardAllPendingWork() { |
| 30 |
int numDiscarded = fExecutor.discardAllPendingWork(); |
| 31 |
fPending.fetch_add(-numDiscarded, std::memory_order_release); |
| 32 |
} |
| 33 |
|
| 34 |
void SkTaskGroup::batch(int N, std::function<void(int)> fn) { |
| 35 |
// TODO: I really thought we had some sort of more clever chunking logic. |
| 36 |
fPending.fetch_add(+N, std::memory_order_relaxed); |
| 37 |
for (int i = 0; i < N; i++) { |
| 38 |
fExecutor.add([fn, i, this] { |
| 39 |
fn(i); |
| 40 |
fPending.fetch_add(-1, std::memory_order_release); |
| 41 |
}); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
bool SkTaskGroup::done() const { |
| 46 |
return fPending.load(std::memory_order_acquire) == 0; |
| 47 |
} |
| 48 |
|
| 49 |
void SkTaskGroup::wait() { |
| 50 |
// Actively help the executor do work until our task group is done. |
| 51 |
// This lets SkTaskGroups nest arbitrarily deep on a single SkExecutor: |
| 52 |
// no thread ever blocks waiting for others to do its work. |
| 53 |
// (We may end up doing work that's not part of our task group. That's fine.) |
| 54 |
while (!this->done()) { |
| 55 |
fExecutor.borrow(); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
SkTaskGroup::Enabler::Enabler(int threads) { |
| 60 |
if (threads) { |
| 61 |
fThreadPool = SkExecutor::MakeLIFOThreadPool(threads); |
| 62 |
SkExecutor::SetDefault(fThreadPool.get()); |
| 63 |
} |
| 64 |
} |