First commit

This commit is contained in:
Samer Afach
2017-01-15 11:16:00 +01:00
commit 1a56e9bc1d
7 changed files with 353 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
#ifndef LOCKGUARD_H
#define LOCKGUARD_H
#include "pthread.h"
/**
* @brief The LockGuard class
* Protects against deadlock by forcing unlocks when going out of scope
*
* The mechanism is quite simple. Constructor locks, destructor unlocks,
* and custom locks and unlocks are possible
*/
class LockGuard_pthread
{
pthread_mutex_t& _lock;
bool is_locked;
public:
LockGuard_pthread(pthread_mutex_t& LockRef);
~LockGuard_pthread();
void lock();
void unlock();
private:
LockGuard_pthread(LockGuard_pthread const &);
void operator=(LockGuard_pthread &);
};
#endif // LOCKGUARD_H

View File

@@ -0,0 +1,89 @@
#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