/usr/include/vigra/threadpool.hxx is in libvigraimpex-dev 1.10.0+git20160211.167be93+dfsg-5ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | /************************************************************************/
/* */
/* Copyright 2014-2015 by Thorsten Beier, Philip Schill */
/* and Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_THREADPOOL_HXX
#define VIGRA_THREADPOOL_HXX
#include <vector>
#include <queue>
#include <stdexcept>
#include <cmath>
#include "mathutil.hxx"
#include "counting_iterator.hxx"
#include "threading.hxx"
namespace vigra
{
/** \addtogroup ParallelProcessing Functions and classes for parallel processing.
*/
//@{
/**\brief Option base class for parallel algorithms.
<b>\#include</b> \<vigra/threadpool.hxx\><br>
Namespace: vigra
*/
class ParallelOptions
{
public:
/** Constants for special settings.
*/
enum {
Auto = -1, ///< Determine number of threads automatically (from <tt>threading::thread::hardware_concurrency()</tt>)
Nice = -2, ///< Use half as many threads as <tt>Auto</tt> would.
NoThreads = 0 ///< Switch off multi-threading (i.e. execute tasks sequentially)
};
ParallelOptions()
: numThreads_(actualNumThreads(Auto))
{}
/** \brief Get desired number of threads.
<b>Note:</b> This function may return 0, which means that multi-threading
shall be switched off entirely. If an algorithm receives this value,
it should revert to a sequential implementation. In contrast, if
<tt>numThread() == 1</tt>, the parallel algorithm version shall be
executed with a single thread.
*/
int getNumThreads() const
{
return numThreads_;
}
/** \brief Get desired number of threads.
In contrast to <tt>numThread()</tt>, this will always return a value <tt>>=1</tt>.
*/
int getActualNumThreads() const
{
return std::max(1,numThreads_);
}
/** \brief Set the number of threads or one of the constants <tt>Auto</tt>,
<tt>Nice</tt> and <tt>NoThreads</tt>.
Default: <tt>ParallelOptions::Auto</tt> (use system default)
This setting is ignored if the preprocessor flag <tt>VIGRA_SINGLE_THREADED</tt>
is defined. Then, the number of threads is set to 0 and all tasks revert to
sequential algorithm implementations. The same can be achieved at runtime
by passing <tt>n = 0</tt> to this function. In contrast, passing <tt>n = 1</tt>
causes the parallel algorithm versions to be executed with a single thread.
Both possibilities are mainly useful for debugging.
*/
ParallelOptions & numThreads(const int n)
{
numThreads_ = actualNumThreads(n);
return *this;
}
private:
// helper function to compute the actual number of threads
static size_t actualNumThreads(const int userNThreads)
{
#ifdef VIGRA_SINGLE_THREADED
return 0;
#else
return userNThreads >= 0
? userNThreads
: userNThreads == Nice
? threading::thread::hardware_concurrency() / 2
: threading::thread::hardware_concurrency();
#endif
}
int numThreads_;
};
/********************************************************/
/* */
/* ThreadPool */
/* */
/********************************************************/
/**\brief Thread pool class to manage a set of parallel workers.
<b>\#include</b> \<vigra/threadpool.hxx\><br>
Namespace: vigra
*/
class ThreadPool
{
public:
/** Create a thread pool from ParallelOptions. The constructor just launches
the desired number of workers. If the number of threads is zero,
no workers are started, and all tasks will be executed in synchronously
in the present thread.
*/
ThreadPool(const ParallelOptions & options)
: stop(false)
{
init(options);
}
/** Create a thread pool with n threads. The constructor just launches
the desired number of workers. If \arg n is <tt>ParallelOptions::Auto</tt>,
the number of threads is determined by <tt>threading::thread::hardware_concurrency()</tt>.
<tt>ParallelOptions::Nice</tt> will create half as many threads.
If <tt>n = 0</tt>, no workers are started, and all tasks will be executed
synchronously in the present thread. If the preprocessor flag
<tt>VIGRA_SINGLE_THREADED</tt> is defined, the number of threads is always set
to zero (i.e. synchronous execution), regardless of the value of \arg n. This
is useful for debugging.
*/
ThreadPool(const int n)
: stop(false)
{
init(ParallelOptions().numThreads(n));
}
/**
* The destructor joins all threads.
*/
~ThreadPool();
/**
* Enqueue a task that will be executed by the thread pool.
* The task result can be obtained using the get() function of the returned future.
* If the task throws an exception, it will be raised on the call to get().
*/
template<class F>
auto enqueueReturning(F&& f) -> threading::future<decltype(f(0))>;
/**
* Enqueue function for tasks without return value.
* This is a special case of the enqueueReturning template function, but
* some compilers fail on <tt>std::result_of<F(int)>::type</tt> for void(int) functions.
*/
template<class F>
threading::future<void> enqueue(F&& f) ;
/**
* Block until all tasks are finished.
*/
void waitFinished()
{
threading::unique_lock<threading::mutex> lock(queue_mutex);
finish_condition.wait(lock, [this](){ return tasks.empty() && (busy == 0); });
}
/**
* Return the number of worker threads.
*/
size_t nThreads() const
{
return workers.size();
}
private:
// helper function to init the thread pool
void init(const ParallelOptions & options);
// need to keep track of threads so we can join them
std::vector<threading::thread> workers;
// the task queue
std::queue<std::function<void(int)> > tasks;
// synchronization
threading::mutex queue_mutex;
threading::condition_variable worker_condition;
threading::condition_variable finish_condition;
bool stop;
threading::atomic_long busy, processed;
};
inline void ThreadPool::init(const ParallelOptions & options)
{
busy.store(0);
processed.store(0);
const size_t actualNThreads = options.getNumThreads();
for(size_t ti = 0; ti<actualNThreads; ++ti)
{
workers.emplace_back(
[ti,this]
{
for(;;)
{
std::function<void(int)> task;
{
threading::unique_lock<threading::mutex> lock(this->queue_mutex);
// will wait if : stop == false AND queue is empty
// if stop == true AND queue is empty thread function will return later
//
// so the idea of this wait, is : If where are not in the destructor
// (which sets stop to true, we wait here for new jobs)
this->worker_condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });
if(!this->tasks.empty())
{
++busy;
task = std::move(this->tasks.front());
this->tasks.pop();
lock.unlock();
task(ti);
++processed;
--busy;
finish_condition.notify_one();
}
else if(stop)
{
return;
}
}
}
}
);
}
}
inline ThreadPool::~ThreadPool()
{
{
threading::unique_lock<threading::mutex> lock(queue_mutex);
stop = true;
}
worker_condition.notify_all();
for(threading::thread &worker: workers)
worker.join();
}
template<class F>
inline auto
ThreadPool::enqueueReturning(F&& f) -> threading::future<decltype(f(0))>
{
typedef decltype(f(0)) result_type;
typedef threading::packaged_task<result_type(int)> PackageType;
auto task = std::make_shared<PackageType>(f);
auto res = task->get_future();
if(workers.size()>0){
{
threading::unique_lock<threading::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace(
[task](int tid)
{
(*task)(std::move(tid));
}
);
}
worker_condition.notify_one();
}
else{
(*task)(0);
}
return res;
}
template<class F>
inline threading::future<void>
ThreadPool::enqueue(F&& f)
{
#if defined(USE_BOOST_THREAD) && \
!defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
// Without variadic templates, boost:thread::packaged_task only
// supports the signature 'R()' (functions with no arguments).
// We bind the thread_id parameter to 0, so this parameter
// must NOT be used in function f (fortunately, this is the case
// for the blockwise versions of convolution, labeling and
// watersheds).
typedef threading::packaged_task<void()> PackageType;
auto task = std::make_shared<PackageType>(std::bind(f, 0));
#else
typedef threading::packaged_task<void(int)> PackageType;
auto task = std::make_shared<PackageType>(f);
#endif
auto res = task->get_future();
if(workers.size()>0){
{
threading::unique_lock<threading::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace(
[task](int tid)
{
#if defined(USE_BOOST_THREAD) && \
!defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
(*task)();
#else
(*task)(std::move(tid));
#endif
}
);
}
worker_condition.notify_one();
}
else{
#if defined(USE_BOOST_THREAD) && \
!defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
(*task)();
#else
(*task)(0);
#endif
}
return res;
}
/********************************************************/
/* */
/* parallel_foreach */
/* */
/********************************************************/
// nItems must be either zero or std::distance(iter, end).
template<class ITER, class F>
inline void parallel_foreach_impl(
ThreadPool & pool,
const std::ptrdiff_t nItems,
ITER iter,
ITER end,
F && f,
std::random_access_iterator_tag
){
std::ptrdiff_t workload = std::distance(iter, end);
vigra_precondition(workload == nItems || nItems == 0, "parallel_foreach(): Mismatch between num items and begin/end.");
const float workPerThread = float(workload)/pool.nThreads();
const std::ptrdiff_t chunkedWorkPerThread = std::max<std::ptrdiff_t>(roundi(workPerThread/3.0), 1);
std::vector<threading::future<void> > futures;
for( ;iter<end; iter+=chunkedWorkPerThread)
{
const size_t lc = std::min(workload, chunkedWorkPerThread);
workload-=lc;
futures.emplace_back(
pool.enqueue(
[&f, iter, lc]
(int id)
{
for(size_t i=0; i<lc; ++i)
f(id, iter[i]);
}
)
);
}
for (auto & fut : futures)
{
fut.get();
}
}
// nItems must be either zero or std::distance(iter, end).
template<class ITER, class F>
inline void parallel_foreach_impl(
ThreadPool & pool,
const std::ptrdiff_t nItems,
ITER iter,
ITER end,
F && f,
std::forward_iterator_tag
){
if (nItems == 0)
nItems = std::distance(iter, end);
std::ptrdiff_t workload = nItems;
const float workPerThread = float(workload)/pool.nThreads();
const std::ptrdiff_t chunkedWorkPerThread = std::max<std::ptrdiff_t>(roundi(workPerThread/3.0), 1);
std::vector<threading::future<void> > futures;
for(;;)
{
const size_t lc = std::min(chunkedWorkPerThread, workload);
workload -= lc;
futures.emplace_back(
pool.enqueue(
[&f, iter, lc]
(int id)
{
auto iterCopy = iter;
for(size_t i=0; i<lc; ++i){
f(id, *iterCopy);
++iterCopy;
}
}
)
);
for (size_t i = 0; i < lc; ++i)
{
++iter;
if (iter == end)
{
vigra_postcondition(workload == 0, "parallel_foreach(): Mismatch between num items and begin/end.");
break;
}
}
if(workload==0)
break;
}
for (auto & fut : futures)
fut.get();
}
// nItems must be either zero or std::distance(iter, end).
template<class ITER, class F>
inline void parallel_foreach_impl(
ThreadPool & pool,
const std::ptrdiff_t nItems,
ITER iter,
ITER end,
F && f,
std::input_iterator_tag
){
size_t num_items = 0;
std::vector<threading::future<void> > futures;
for (; iter != end; ++iter)
{
auto item = *iter;
futures.emplace_back(
pool.enqueue(
[&f, &item](int id){
f(id, item);
}
)
);
++num_items;
}
vigra_postcondition(num_items == nItems || nItems == 0, "parallel_foreach(): Mismatch between num items and begin/end.");
for (auto & fut : futures)
fut.get();
}
// Runs foreach on a single thread.
// Used for API compatibility when the numbe of threads is 0.
template<class ITER, class F>
inline void parallel_foreach_single_thread(
ITER begin,
ITER end,
F && f,
const std::ptrdiff_t nItems = 0
){
size_t n = 0;
for (; begin != end; ++begin)
{
f(0, *begin);
++n;
}
vigra_postcondition(n == nItems || nItems == 0, "parallel_foreach(): Mismatch between num items and begin/end.");
}
/** \brief Apply a functor to all items in a range in parallel.
Create a thread pool (or use an existing one) to apply the functor \arg f
to all items in the range <tt>[begin, end)</tt> in parallel. \arg f must
be callable with two arguments of type <tt>size_t</tt> and <tt>T</tt>, where
the first argument is the thread index (starting at 0) and T is convertible
from the iterator's <tt>reference_type</tt> (i.e. the result of <tt>*begin</tt>).
If the iterators are forward iterators (<tt>std::forward_iterator_tag</tt>), you
can provide the optional argument <tt>nItems</tt> to avoid the a
<tt>std::distance(begin, end)</tt> call to compute the range's length.
Parameter <tt>nThreads</tt> controls the number of threads. <tt>parallel_foreach</tt>
will split the work into about three times as many parallel tasks.
If <tt>nThreads = ParallelOptions::Auto</tt>, the number of threads is set to
the machine default (<tt>std::thread::hardware_concurrency()</tt>).
If <tt>nThreads = 0</tt>, the function will not use threads,
but will call the functor sequentially. This can also be enforced by setting the
preprocessor flag <tt>VIGRA_SINGLE_THREADED</tt>, ignoring the value of
<tt>nThreads</tt> (useful for debugging).
<b> Declarations:</b>
\code
namespace vigra {
// pass the desired number of threads or ParallelOptions::Auto
// (creates an internal thread pool accordingly)
template<class ITER, class F>
void parallel_foreach(int64_t nThreads,
ITER begin, ITER end,
F && f,
const uint64_t nItems = 0);
// use an existing thread pool
template<class ITER, class F>
void parallel_foreach(ThreadPool & pool,
ITER begin, ITER end,
F && f,
const uint64_t nItems = 0);
// pass the integers from 0 ... (nItems-1) to the functor f,
// using the given number of threads or ParallelOptions::Auto
template<class F>
void parallel_foreach(int64_t nThreads,
uint64_t nItems,
F && f);
// likewise with an existing thread pool
template<class F>
void parallel_foreach(ThreadPool & threadpool,
uint64_t nItems,
F && f);
}
\endcode
<b>Usage:</b>
\code
#include <iostream>
#include <algorithm>
#include <vector>
#include <vigra/threadpool.hxx>
using namespace std;
using namespace vigra;
int main()
{
size_t const n_threads = 4;
size_t const n = 2000;
vector<int> input(n);
auto iter = input.begin(),
end = input.end();
// fill input with 0, 1, 2, ...
iota(iter, end, 0);
// compute the sum of the elements in the input vector.
// (each thread computes the partial sum of the items it sees
// and stores the sum at the appropriate index of 'results')
vector<int> results(n_threads, 0);
parallel_foreach(n_threads, iter, end,
// the functor to be executed, defined as a lambda function
// (first argument: thread ID, second argument: result of *iter)
[&results](size_t thread_id, int items)
{
results[thread_id] += items;
}
);
// collect the partial sums of all threads
int sum = accumulate(results.begin(), results.end(), 0);
cout << "The sum " << sum << " should be equal to " << (n*(n-1))/2 << endl;
}
\endcode
*/
doxygen_overloaded_function(template <...> void parallel_foreach)
template<class ITER, class F>
inline void parallel_foreach(
ThreadPool & pool,
ITER begin,
ITER end,
F && f,
const std::ptrdiff_t nItems = 0)
{
if(pool.nThreads()>1)
{
parallel_foreach_impl(pool,nItems, begin, end, f,
typename std::iterator_traits<ITER>::iterator_category());
}
else
{
parallel_foreach_single_thread(begin, end, f, nItems);
}
}
template<class ITER, class F>
inline void parallel_foreach(
int64_t nThreads,
ITER begin,
ITER end,
F && f,
const std::ptrdiff_t nItems = 0)
{
ThreadPool pool(nThreads);
parallel_foreach(pool, begin, end, f, nItems);
}
template<class F>
inline void parallel_foreach(
int64_t nThreads,
std::ptrdiff_t nItems,
F && f)
{
auto iter = range(nItems);
parallel_foreach(nThreads, iter, iter.end(), f, nItems);
}
template<class F>
inline void parallel_foreach(
ThreadPool & threadpool,
std::ptrdiff_t nItems,
F && f)
{
auto iter = range(nItems);
parallel_foreach(threadpool, iter, iter.end(), f, nItems);
}
//@}
} // namespace vigra
#endif // VIGRA_THREADPOOL_HXX
|