class mrpt::WorkerThreadsPool

Overview

A thread pool: it defines a fixed number of threads, which will remain blocked waiting for jobs to be assigned, via WorkerThreadsPool::enqueue(), which accepts any function-like object with arbitrary parameters and returns a std::future<ReturnType> which can be used to wait and/or retrieve the function output at any moment in time afterwards.

In case of more tasks assigned than available free threads, two policies exist:

Partly based on: https://github.com/progschj/ThreadPool (ZLib license)

(New in MRPT 2.1.0)

#include <mrpt/core/WorkerThreadsPool.h>

class WorkerThreadsPool
{
public:
    // enums

    enum queue_policy_t;

    // construction

    WorkerThreadsPool();

    WorkerThreadsPool(
        std::size_t num_threads,
        queue_policy_t p = POLICY_FIFO,
        const std::string& threadsName = "WorkerThreadsPool"
        );

    // methods

    void resize(std::size_t num_threads);
    std::size_t size() const;
    void clear();

    template <class F, class... Args>
    auto enqueue(F&& f, Args&&... args);

    std::size_t pendingTasks() const;
    void name(const std::string& name);
    std::string name() const;
};

Methods

std::size_t size() const

Get number of working threads.

(New in MRPT 2.4.2)

void clear()

Stops and deletes all worker threads.

template <class F, class... Args>
auto enqueue(F&& f, Args&&... args)

Enqueue one new working item, to be executed by threads when any is available.

std::size_t pendingTasks() const

Returns the number of enqueued tasks, currently waiting for a free working thread to process them.

void name(const std::string& name)

Sets the private thread names of threads in this pool.

Names can be seen from debuggers, profilers, etc. and will follow the format ${name}[i] with ${name} the value supplied in this method (Method new in MRPT 2.1.5)

std::string name() const

Returns the base name of threads in this pool.