1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
#ifndef THREAD_HELPERS_COMMON_HPP
#define THREAD_HELPERS_COMMON_HPP
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
template <typename Function>
void
parallel_exec(size_t concurrency, Function f)
{
std::vector<std::thread> threads;
threads.reserve(concurrency);
for (size_t i = 0; i < concurrency; ++i) {
threads.emplace_back(f, i);
}
for (auto &t : threads) {
t.join();
}
}
/*
* This function executes 'concurrency' threads and provides
* 'syncthreads' method (synchronization barrier) for f()
*/
template <typename Function>
void
parallel_xexec(size_t concurrency, Function f)
{
std::condition_variable cv;
std::mutex m;
std::unique_ptr<size_t> counter =
std::unique_ptr<size_t>(new size_t(0));
auto syncthreads = [&] {
std::unique_lock<std::mutex> lock(m);
(*counter)++;
if (*counter < concurrency)
cv.wait(lock, [&] { return *counter >= concurrency; });
else
/*
* notify_call could be called outside of a lock
* (it would perform better) but drd complains
* in that case
*/
cv.notify_all();
};
parallel_exec(concurrency, [&](size_t tid) { f(tid, syncthreads); });
}
/*
* This function executes 'concurrency' threads and wait for all of them to
* finish executing f before calling join().
*/
template <typename Function>
void
parallel_exec_with_sync(size_t concurrency, Function f)
{
parallel_xexec(concurrency,
[&](size_t tid, std::function<void(void)> syncthreads) {
f(tid);
syncthreads();
});
}
#endif /* THREAD_HELPERS_COMMON_HPP */
|