bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Threads, parallel loops and seeds

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.

What you need

Nothing beyond bitsim itself. See Installing bitsim.

The pieces

What it does
ThreadPool a fixed number of threads; submit(f, args...) queues a task and returns the std::future of its result
parallel_for(begin, end, f) calls f(i) for every index, cut into chunks of consecutive indices; returns when all are done
parallel_map(n, f) returns f(0), ..., f(n - 1), in the order of the index
task_seed(seed, task) an unrelated seed for every task, for tasks that draw random numbers
default_thread_pool() the pool the two functions use when given none: one thread per core, or BITSIM_NUM_THREADS

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.

Running the example

./thread_pool_basics

Output

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.

  1. A task that throws does not take its thread down: the exception waits in the future, and get() throws it.
  2. parallel_for gives the calling thread a chunk as well, so a pool of 4 threads works on 5 chunks at once. A pool of one thread therefore already runs two pieces of work at a time; to time one thread, use a plain loop, as Dead reckoning drift, on all the cores does.
  3. The tasks of part 3 sleep longer the smaller their index, so they finish backwards, but parallel_map puts every result in the slot of its index.
  4. A generator shared by threads is a data race, and even with a lock the numbers each task got would depend on which thread asked first. With a generator per task, seeded with task_seed(), the walks are the same in a plain loop and on 8 threads. Seeds seed + task would work too, but generators seeded with neighbouring numbers start with numbers that are alike; task_seed mixes the two with SplitMix64.
  5. If calls throw, parallel_for still waits for every chunk, since they all use f, and then rethrows the first exception. A parallel_for called from a task of its own pool runs on that thread, in order: waiting for the pool from inside it could leave no thread to do the work.

Things to try

  1. Make roots a std::vector<bool> and set roots[i] = i % 2. Why is that a data race, when a std::vector<char> is not?
  2. Time part 2 with a grain of 1 and of 100000 (the last argument of parallel_for).
  3. Seed the walks with 2024 + task and compare the first steps of neighbouring walks.

The code

// The concurrency utilities of bitsim, one at a time: a pool of threads and the futures of its
// tasks, parallel_for over a range of indices, parallel_map with results in order, seeds for
// tasks that draw random numbers, and what happens when a task throws.
//
// Usage: thread_pool_basics
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <mutex>
#include <random>
#include <stdexcept>
#include <thread>
#include <vector>
{
// A random walk of n steps of +1 or -1, from its own generator
{
std::mt19937 rng(static_cast<std::mt19937::result_type>(seed));
std::bernoulli_distribution up(0.5);
real_t x = 0.0;
for (uint_t i = 0; i < n; ++i)
{
x += up(rng) ? 1.0 : -1.0;
}
return x;
}
void run()
{
bitsim::utils::io::print_title("1. A pool of threads");
ThreadPool pool(4);
std::cout << " The pool has " << pool.size() << " threads; this machine has "
<< ThreadPool::default_n_threads() << " for the default pool\n";
// submit() queues a task and gives back the future of its result
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";
// an exception in a task comes out of the future's get()
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";
}
bitsim::utils::io::print_title("2. parallel_for");
// every index writes only its own element, so the threads never touch the same memory
const uint_t N = 1000000;
std::vector<real_t> roots(N);
std::mutex mutex;
std::map<std::thread::id, std::pair<uint_t, uint_t>> chunks; // thread -> first, last index
0, N,
[&](uint_t i)
{
roots[i] = std::sqrt(static_cast<real_t>(i));
if (i % 10000 == 0)
{
// a lock only to record who did what; the work itself needs none
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";
bitsim::utils::io::print_title("3. parallel_map keeps the order");
// the tasks finish in a scrambled order, the results still come back by index
const auto squares = parallel_map(
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";
bitsim::utils::io::print_title("4. Seeds for random tasks");
// each task gets its own generator, seeded with task_seed(seed, task); the results depend on
// the seed and the task only, not on the threads that ran them
const auto walk = [](std::size_t task) { return random_walk(task_seed(2024, task), 10000); };
std::vector<real_t> on_one;
for (std::size_t task = 0; task < 16; ++task)
{
on_one.push_back(walk(task));
}
const auto on_many = parallel_map(16, walk, default_thread_pool());
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";
bitsim::utils::io::print_title("5. Exceptions and nesting");
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";
}
// a parallel_for inside a task of the same pool runs on that task's thread, so a pool of one
// thread cannot wait for itself
auto nested = one_thread.submit(
[&one_thread]
{
std::vector<int> v(100, 1);
0, v.size(), [&v](uint_t i) { v[i] *= 3; }, one_thread);
int sum = 0;
for (const int x : v)
{
sum += x;
}
return sum;
});
std::cout << " a parallel_for nested in a task of a one-thread pool finished, sum = "
<< nested.get() << "\n";
}
} // namespace thread_pool_basics
int main()
{
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,...