2011-09-27 17:48:46 +00:00
|
|
|
|
// This code is in the public domain -- Ignacio Casta<74>o <castano@gmail.com>
|
|
|
|
|
|
|
|
|
|
#include "ParallelFor.h"
|
|
|
|
|
#include "Thread.h"
|
|
|
|
|
#include "Atomic.h"
|
|
|
|
|
#include "ThreadPool.h"
|
|
|
|
|
|
2011-10-11 18:52:24 +00:00
|
|
|
|
#include "nvcore/Utils.h" // toI32
|
|
|
|
|
|
2011-09-27 17:48:46 +00:00
|
|
|
|
using namespace nv;
|
|
|
|
|
|
2012-02-14 16:35:42 +00:00
|
|
|
|
#define ENABLE_PARALLEL_FOR 1
|
2011-09-27 17:48:46 +00:00
|
|
|
|
|
2012-07-20 16:32:26 +00:00
|
|
|
|
static void worker(void * arg) {
|
2011-09-27 17:48:46 +00:00
|
|
|
|
ParallelFor * owner = (ParallelFor *)arg;
|
|
|
|
|
|
|
|
|
|
while(true) {
|
|
|
|
|
// Consume one element at a time. @@ Might be more efficient to have custom grain.
|
|
|
|
|
uint i = atomicIncrement(&owner->idx);
|
|
|
|
|
if (i > owner->count) {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
owner->task(owner->context, i - 1);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ParallelFor::ParallelFor(ForTask * task, void * context) : task(task), context(context) {
|
|
|
|
|
#if ENABLE_PARALLEL_FOR
|
|
|
|
|
pool = ThreadPool::acquire();
|
|
|
|
|
#endif
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ParallelFor::~ParallelFor() {
|
|
|
|
|
#if ENABLE_PARALLEL_FOR
|
|
|
|
|
ThreadPool::release(pool);
|
|
|
|
|
#endif
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-24 19:14:49 +00:00
|
|
|
|
void ParallelFor::run(uint count, bool calling_thread_process_work /*=false*/) {
|
2011-09-27 17:48:46 +00:00
|
|
|
|
#if ENABLE_PARALLEL_FOR
|
|
|
|
|
storeRelease(&this->count, count);
|
|
|
|
|
|
|
|
|
|
// Init atomic counter to zero.
|
|
|
|
|
storeRelease(&idx, 0);
|
|
|
|
|
|
|
|
|
|
// Start threads.
|
|
|
|
|
pool->start(worker, this);
|
|
|
|
|
|
2015-03-24 19:14:49 +00:00
|
|
|
|
if (calling_thread_process_work) {
|
|
|
|
|
worker(this);
|
|
|
|
|
}
|
|
|
|
|
|
2011-09-27 17:48:46 +00:00
|
|
|
|
// Wait for all threads to complete.
|
|
|
|
|
pool->wait();
|
|
|
|
|
|
|
|
|
|
nvDebugCheck(idx >= count);
|
|
|
|
|
#else
|
2011-10-11 18:52:24 +00:00
|
|
|
|
for (int i = 0; i < toI32(count); i++) {
|
2011-09-27 17:48:46 +00:00
|
|
|
|
task(context, i);
|
|
|
|
|
}
|
|
|
|
|
#endif
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|