| 1 |
#include <pbcopper/parallel/FireAndForget.h> |
| 2 |
|
| 3 |
#include <atomic> |
| 4 |
#include <exception> |
| 5 |
|
| 6 |
namespace PacBio { |
| 7 |
namespace Parallel { |
| 8 |
void Dispatch(Parallel::FireAndForget* const faf, const int32_t numEntries, |
| 9 |
const std::function<void(int32_t)>& callback) |
| 10 |
{ |
| 11 |
if (faf) { |
| 12 |
std::exception_ptr exc; |
| 13 |
std::atomic_bool abort{false}; |
| 14 |
|
| 15 |
int32_t fafCounter{0}; |
| 16 |
std::condition_variable condVar; |
| 17 |
std::mutex m; |
| 18 |
const auto Submit = [&](int32_t i) { |
| 19 |
try { |
| 20 |
callback(i); |
| 21 |
} catch (...) { |
| 22 |
std::unique_lock<std::mutex> lock{m}; |
| 23 |
if (!abort) { |
| 24 |
exc = std::current_exception(); |
| 25 |
abort = true; |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
std::unique_lock<std::mutex> lock{m}; |
| 30 |
if ((++fafCounter == numEntries) || abort) { |
| 31 |
condVar.notify_one(); |
| 32 |
} |
| 33 |
}; |
| 34 |
|
| 35 |
for (int32_t i = 0; i < numEntries; ++i) { |
| 36 |
faf->ProduceWith(Submit, i); |
| 37 |
} |
| 38 |
|
| 39 |
{ |
| 40 |
std::unique_lock<std::mutex> lock{m}; |
| 41 |
condVar.wait(lock, [&fafCounter, numEntries, &abort] { |
| 42 |
return (fafCounter == numEntries) || abort; |
| 43 |
}); |
| 44 |
} |
| 45 |
|
| 46 |
if (abort) { |
| 47 |
std::rethrow_exception(exc); |
| 48 |
} |
| 49 |
} else { |
| 50 |
for (int32_t i = 0; i < numEntries; ++i) { |
| 51 |
callback(i); |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
} // namespace Parallel |
| 56 |
} // namespace PacBio |