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

61 lines
1.2 KiB
C++
Raw 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()
{};
void newProducer( 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-08 16:53:53 +02:00
}
2020-07-09 18:09:10 +02:00
void newConsumer( 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
};
#endif