Many computations in robotics are a lot of small pieces of work that do not depend on each other: one simulation per seed, one picture per frame, one ray per beam of a sensor. bitsim's bitsim/utils/concurrency runs such work on all the cores. This example shows its parts one at a time.
The rule for the work: each call should write only to what is its own, an element of a vector of results for example, and read what nobody writes. Then the threads never need a lock.
1. A pool of threads
The pool has 4 threads; this machine has 8 for the default pool
area of a circle of radius 2: 12.5664
the task ran on a thread of the pool: true; this thread is one of them: false
the failing task threw: no square root of -1
2. parallel_for
sqrt(999999) = 999.999. The range was cut into 5 chunks of consecutive indices, one for the calling thread and one for each thread of the pool; 4 different threads ran them, since a thread that finishes early takes the next chunk in the queue
3. parallel_map keeps the order
squares: 0 1 4 9 16 25 36 49
4. Seeds for random tasks
the end of 16 random walks of 10000 steps: -102 24 -34 -48 -2 -38 -42 16 -228 -108 66 -18 -170 172 78 -82
the same in a plain loop and on the threads: true
task_seed(2024, 0) = 11487996472437173461, task_seed(2024, 1) = 1793612131670815442
5. Exceptions and nesting
parallel_for waited for every chunk, then rethrew: index 42 is not allowed
a parallel_for nested in a task of a one-thread pool finished, sum = 300
The number of threads that ran the chunks in part 2 changes from run to run; everything else is the same every time.
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <mutex>
#include <random>
#include <stdexcept>
#include <thread>
#include <vector>
{
{
std::mt19937 rng(static_cast<std::mt19937::result_type>(seed));
std::bernoulli_distribution up(0.5);
for (
uint_t i = 0; i < n; ++i)
{
x += up(rng) ? 1.0 : -1.0;
}
return x;
}
{
std::cout << " The pool has " << pool.size() << " threads; this machine has "
auto area = pool.submit([](
real_t r) {
return M_PI * r * r; }, 2.0);
auto inside = pool.submit([&pool] { return pool.is_worker_thread(); });
std::cout << " area of a circle of radius 2: " << area.get() << "\n";
std::cout << " the task ran on a thread of the pool: " << std::boolalpha << inside.get()
<< "; this thread is one of them: " << pool.is_worker_thread() << "\n";
auto failing = pool.submit([]() ->
real_t {
throw std::domain_error(
"no square root of -1"); });
try
{
failing.get();
}
catch (const std::domain_error &e)
{
std::cout << " the failing task threw: " << e.what() << "\n\n";
}
std::vector<real_t> roots(N);
std::mutex mutex;
std::map<std::thread::id, std::pair<uint_t, uint_t>> chunks;
0, N,
{
roots[i] = std::sqrt(
static_cast<real_t>(i));
if (i % 10000 == 0)
{
std::lock_guard<std::mutex> lock(mutex);
auto [itr, fresh] = chunks.try_emplace(std::this_thread::get_id(), i, i);
if (!fresh)
{
itr->second.first = std::min(itr->second.first, i);
itr->second.second = std::max(itr->second.second, i);
}
}
},
pool);
std::cout << " sqrt(999999) = " << roots.back() << ". The range was cut into "
<< pool.size() + 1 << " chunks of consecutive indices, one for the calling thread "
<< "and one for each thread of the pool; " << chunks.size()
<< " different threads ran them, since a thread that finishes early takes the next "
<< "chunk in the queue\n\n";
8,
[](std::size_t i)
{
std::this_thread::sleep_for(std::chrono::milliseconds((8 - i) * 5));
return i * i;
},
pool);
std::cout << " squares:";
for (const auto s : squares)
{
std::cout << " " << s;
}
std::cout << "\n\n";
std::vector<real_t> on_one;
for (std::size_t task = 0; task < 16; ++task)
{
on_one.push_back(walk(task));
}
std::cout << " the end of 16 random walks of 10000 steps:";
for (const auto x : on_many)
{
std::cout << " " << x;
}
std::cout << "\n the same in a plain loop and on the threads: " << (on_one == on_many) << "\n";
std::cout <<
" task_seed(2024, 0) = " <<
task_seed(2024, 0)
<<
", task_seed(2024, 1) = " <<
task_seed(2024, 1) <<
"\n\n";
try
{
0, 100,
[](int i)
{
if (i == 42)
{
throw std::out_of_range("index 42 is not allowed");
}
},
pool);
}
catch (const std::out_of_range &e)
{
std::cout << " parallel_for waited for every chunk, then rethrew: " << e.what() << "\n";
}
[&one_thread]
{
std::vector<int> v(100, 1);
0, v.size(), [&v](
uint_t i) { v[i] *= 3; }, one_thread);
for (const int x : v)
{
}
});
std::cout << " a parallel_for nested in a task of a one-thread pool finished, sum = "
<< nested.get() << "\n";
}
}
{
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
A fixed number of threads that run the tasks given to them, in the order given.
Definition thread_pool.h:33
static uint_t default_n_threads()
The number of threads to use when none is given: the environment variable BITSIM_NUM_THREADS if it is...
Definition thread_pool.cpp:17
int main()
Definition discounted_returns.cpp:19
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
Definition concurrent_queue.h:15
uint_t task_seed(uint_t base_seed, uint_t task) noexcept
A seed for task task, made from base_seed.
Definition parallel.h:148
auto parallel_map(std::size_t n, F &&f, ThreadPool &pool=default_thread_pool()) -> std::vector< std::invoke_result_t< F &, std::size_t > >
Compute f(0), f(1), ..., f(n - 1) on the threads of pool.
Definition parallel.h:119
void parallel_for(Index begin, Index end, F &&f, ThreadPool &pool=default_thread_pool(), Index grain=1)
Call f(i) for every i in [begin, end), spread over the threads of pool.
Definition parallel.h:38
ThreadPool & default_thread_pool()
The pool that parallel_for() and parallel_map() use when given none. It starts ThreadPool::default_n_...
Definition thread_pool.cpp:77
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
const uint_t N
Definition importance_sampling.cpp:30
Rank one_thread(uint_t n_rounds, uint_t n_copies)
Definition ppo_distributed.cpp:236
Definition thread_pool_basics.cpp:24
void run()
Definition thread_pool_basics.cpp:43
real_t random_walk(uint_t seed, uint_t n)
Definition thread_pool_basics.cpp:31
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...