1
0
Fork 0
This repository has been archived on 2021-11-03. You can view files and clone it, but cannot push or open issues or pull requests.
uni-m.cds-adv-prog/ex10/threadpool.hh

80 lines
1.6 KiB
C++
Raw Permalink Normal View History

2020-07-08 16:53:53 +02:00
// ThreadPool.hh
#include "shared_queue.hh"
#include <thread>
#include <vector>
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
2020-07-09 18:09:10 +02:00
// Implementations for producers and consumers
void producer( const int id, SharedQueue<int>& _q, int max_t, int max_n );
void consumer( const int id, SharedQueue<int>& _q, int max_t, int max_n );
2020-07-08 16:53:53 +02:00
class ThreadPool
{
public:
2020-07-09 18:09:10 +02:00
ThreadPool() :
_q(),
_consumers(),
_producers()
{};
2020-07-09 22:52:04 +02:00
void addProducer( int max_t = 3000, int max_n = 10)
2020-07-08 16:53:53 +02:00
{
2020-07-09 18:09:10 +02:00
std::thread * tp = new std::thread( producer, _producers.size(), std::ref(_q), max_t, max_n );
_producers.push_back(tp);
2020-07-09 21:22:39 +02:00
2020-07-08 16:53:53 +02:00
}
2020-07-09 22:52:04 +02:00
void addConsumer( int max_t = 2000, int max_n = 10)
2020-07-08 16:53:53 +02:00
{
2020-07-09 18:09:10 +02:00
std::thread * tp = new std::thread( consumer, _consumers.size(), std::ref(_q), max_t, max_n );
_consumers.push_back(tp);
2020-07-08 16:53:53 +02:00
}
void run()
{
// join all producers
2020-07-09 18:09:10 +02:00
for ( int i = 0; i < _producers.size() ; i++ )
2020-07-08 16:53:53 +02:00
{
2020-07-09 18:09:10 +02:00
(*_producers[i]).join();
2020-07-08 16:53:53 +02:00
}
// join all consumers
2020-07-09 18:09:10 +02:00
for ( int i = 0; i < _consumers.size() ; i++ )
2020-07-08 16:53:53 +02:00
{
2020-07-09 18:09:10 +02:00
(*_consumers[i]).join();
2020-07-08 16:53:53 +02:00
}
}
private:
// Consumer and Producers threads
2020-07-09 18:09:10 +02:00
std::vector<std::thread * > _consumers;
std::vector<std::thread * > _producers;
2020-07-08 16:53:53 +02:00
// queue
2020-07-09 18:09:10 +02:00
SharedQueue<int> _q;
2020-07-08 16:53:53 +02:00
};
2020-07-09 22:52:04 +02:00
#if ENABLE_PYBIND
/*
* Define Python access
*/
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(ThreadPool, tp)
{
py::class_<ThreadPool>( tp, "ThreadPool")
.def(py::init())
.def("addProducer", &ThreadPool::addProducer, "Add a new Producer to the Pool")
.def("addConsumer", &ThreadPool::addConsumer, "Add a new Consumer to the Pool")
.def("run", &ThreadPool::run, "Run all registered Producers and Consumers");
}
#endif
2020-07-08 16:53:53 +02:00
#endif