Switch to futures

This commit is contained in:
Christian Biesinger
2019-10-08 17:25:26 -05:00
parent 52300df201
commit d13d16c4d8
3 changed files with 16 additions and 22 deletions

View File

@@ -68,9 +68,7 @@ parallel_for_each (RandomIt first, RandomIt last, RangeFunction callback)
parallel_for_pool.start (n_threads); parallel_for_pool.start (n_threads);
} }
std::mutex mtx; std::future<void> futures[n_threads];
std::condition_variable cv;
int num_finished = 0;
size_t n_elements = last - first; size_t n_elements = last - first;
if (n_threads > 1 && 2 * n_threads <= n_elements) if (n_threads > 1 && 2 * n_threads <= n_elements)
@@ -79,11 +77,8 @@ parallel_for_each (RandomIt first, RandomIt last, RangeFunction callback)
for (int i = 0; i < n_threads; ++i) for (int i = 0; i < n_threads; ++i)
{ {
RandomIt end = first + elts_per_thread; RandomIt end = first + elts_per_thread;
parallel_for_pool.post_task ([&, first, end] () { futures[i] = parallel_for_pool.post_task ([&, first, end] () {
callback (first, end); callback (first, end);
std::unique_lock<std::mutex> lck (mtx);
num_finished++;
cv.notify_all ();
}); });
first = end; first = end;
} }
@@ -94,15 +89,10 @@ parallel_for_each (RandomIt first, RandomIt last, RangeFunction callback)
/* Process all the remaining elements in the main thread. */ /* Process all the remaining elements in the main thread. */
callback (first, last); callback (first, last);
if (n_threads) #ifdef CXX_STD_THREAD
{ for (size_t i = 0; i < n_threads; ++i)
for (;;) { futures[i].wait ();
std::unique_lock<std::mutex> lck (mtx); #endif /* CXX_STD_THREAD */
if (num_finished == n_threads)
break;
cv.wait (lck);
}
}
} }
} }

View File

@@ -40,7 +40,7 @@ thread_pool::thread_function ()
break; break;
if (m_tasks.empty ()) if (m_tasks.empty ())
continue; continue;
t = m_tasks.front(); t = std::move (m_tasks.front());
m_tasks.pop(); m_tasks.pop();
} }
t (); t ();

View File

@@ -8,6 +8,7 @@
#include <atomic> #include <atomic>
#include <mutex> #include <mutex>
#include <condition_variable> #include <condition_variable>
#include <future>
namespace gdb { namespace gdb {
@@ -20,11 +21,14 @@ class thread_pool {
void start(size_t num_threads); void start(size_t num_threads);
typedef std::function<void ()> task; typedef std::packaged_task<void()> task;
void post_task(task t) { std::future<void> post_task(std::function<void ()> func) {
task t(func);
std::future<void> f = t.get_future();
std::lock_guard<std::mutex> guard (m_tasks_mutex); std::lock_guard<std::mutex> guard (m_tasks_mutex);
m_tasks.push (t); m_tasks.push (std::move (t));
m_tasks_cv.notify_one (); m_tasks_cv.notify_one ();
return f;
} }
private: private: