90 lines
2.4 KiB
C
90 lines
2.4 KiB
C
|
#ifndef THREADPOOL_H
|
||
|
#define THREADPOOL_H
|
||
|
|
||
|
#include <queue>
|
||
|
#include <vector>
|
||
|
#include <functional>
|
||
|
#include <string>
|
||
|
#include <iostream>
|
||
|
#include <sstream>
|
||
|
|
||
|
#include "pthread.h"
|
||
|
|
||
|
#include "LockGuard_pthread.h"
|
||
|
|
||
|
/**
|
||
|
* @brief The ThreadPool class
|
||
|
* A basic thread pool implementation using pthread
|
||
|
*
|
||
|
* Call with the constructor ThreadPool::ThreadPool(N) to get N threads.
|
||
|
* The default constructor will detect the number of available cores/core threads and use it.
|
||
|
* Constructor throws std::runtime_error() on failure to spawn processes.
|
||
|
*
|
||
|
*
|
||
|
* Add tasks using ThreadPool::push_task(function, args). More info at the function description.
|
||
|
*
|
||
|
* Use ThreadPool::finish() to wait for all tasks to process and join all threads.
|
||
|
*
|
||
|
*
|
||
|
*
|
||
|
*
|
||
|
*/
|
||
|
class ThreadPool_pthread
|
||
|
{
|
||
|
pthread_cond_t task_queue_cond; //signaled when a new task is pushed
|
||
|
pthread_cond_t thread_finished_cond; //signaled when a thread finishes and no more is there to do
|
||
|
pthread_mutex_t mutex;
|
||
|
bool no_more_to_push;
|
||
|
|
||
|
typedef void*(*FunctionType)(void*);
|
||
|
|
||
|
//queue of tasks as an std::queue of std::pair of functions and args
|
||
|
std::queue<std::pair<FunctionType,void*> > tasks_queue;
|
||
|
|
||
|
|
||
|
void launch_threads();
|
||
|
int num_of_threads; //stores the number of threads requested
|
||
|
std::vector<pthread_t> threads_objects;
|
||
|
friend void* _thread_worker(void*);
|
||
|
bool joined; //prevents rejoining twice, true when all threads are joined
|
||
|
long threads_running; //keeps track of threads that are executing tasks
|
||
|
void join_all();
|
||
|
|
||
|
public:
|
||
|
ThreadPool_pthread(int threads_count);
|
||
|
virtual ~ThreadPool_pthread();
|
||
|
|
||
|
/**
|
||
|
* @brief push_task
|
||
|
* Adds a task to the processing queue
|
||
|
*
|
||
|
* Results are passed through parameters too. No return value is considered.
|
||
|
*
|
||
|
* @param function
|
||
|
* Function pointer to the function to be executed.
|
||
|
* The function is of type void*(void*)
|
||
|
* All parameters should be passed through a single void pointer
|
||
|
*
|
||
|
* @param params
|
||
|
* Parameters of the function as void*.
|
||
|
*/
|
||
|
void push_task(FunctionType function, void* params);
|
||
|
|
||
|
/**
|
||
|
* @brief finish
|
||
|
* Waits for all threads to finish and joins them.
|
||
|
*/
|
||
|
void finish();
|
||
|
};
|
||
|
|
||
|
template <typename T>
|
||
|
std::string _to_string(T const& value)
|
||
|
{
|
||
|
std::stringstream sstr;
|
||
|
|
||
|
sstr << value;
|
||
|
return sstr.str();
|
||
|
}
|
||
|
|
||
|
#endif // THREADPOOL_H
|