threadPool

Header file (declarations and definitions because of template functions) for the implementation of a generic thread pool

template<class jobtype>
class default_comp
#include <threadPool.h>

Default comparator for priority_queue in threadPool &#8212; no comparison.

First in first out, not sorting

Public Functions

inline bool operator()(jobtype j, jobtype k)
template<class jobtype = int, class comparator = default_comp<jobtype>>
class threadPool
#include <threadPool.h>

Class for creating a pool of threads to asynchronously distribute work.

Template parameters:

jobtype defines a structure or class that represents a job or task

comparator defines how to compare jobs for sorting the list

Default options correspond to jobs being defined by an integer job_id, and no sorting of the list (first in first out)

Public Functions

inline explicit threadPool(std::size_t numThreads, std::function<void(int, jobtype)> work_fn)

Constructor &#8212; starts thread pool running.

inline ~threadPool()

Destructor &#8212; stops threads.

inline void enqueue(jobtype job_id)

Places jobs in queue to wait for scheduling.

job_id is sorted if a comparator is provided

inline int get_num_threads()

Get the number of threads being used by the thread pool.

inline int get_queue_length()

Get the current length of the job queue.

Private Functions

inline void start(std::size_t numThreads)

Starts thread pool &#8212; launches each thread, which continually check for work.

inline void stop() noexcept

Stops thread pool.

Waits for all threads to end and joins them

Finishes the thread pool before ending

Private Members

std::vector<std::thread> Threads

Vector for thread ids

std::condition_variable EventVar

Condition Variable

std::mutex EventMutex

Lock to prevent memory races

bool stopping = false

Boolean stop condition

int numThreads_internal

Number of threads in pool

std::function<void(int, jobtype)> work_fn_internal

Function for each thread to perform &#8212; Takes arguments thread_id and jobtype job

std::priority_queue<jobtype, std::vector<jobtype>, comparator> Tasks

Queue of jobs