66 lines
1.4 KiB
C++
66 lines
1.4 KiB
C++
// ThreadPool.hh
|
|
#include "shared_queue.hh"
|
|
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
#ifndef THREAD_POOL_H
|
|
#define THREAD_POOL_H
|
|
|
|
class ThreadPool
|
|
{
|
|
public:
|
|
|
|
/**
|
|
* @param int max_t Maximum time in milliseconds for a producer iteration.
|
|
* @param int max_n Maximum number of iterations.
|
|
* @return std::thread The created thread.
|
|
*/
|
|
std::thread newProducer( int max_t = 3000, int max_n = 10)
|
|
{
|
|
std::thread t( producer, std::ref(q), producers.size(), max_t, max_n );
|
|
producers.push_back(t);
|
|
|
|
return t;
|
|
}
|
|
|
|
std::thread newConsumer( int max_t = 2000, int max_n = 10)
|
|
{
|
|
std::thread cons( consumer, std::ref(q), consumers.size(), max_t, max_n );
|
|
consumers.push_back(cons);
|
|
|
|
return cons;
|
|
}
|
|
|
|
void run()
|
|
{
|
|
// join all producers
|
|
for ( int i = 0; i < producers.size() ; i++ )
|
|
{
|
|
producers[i].join();
|
|
}
|
|
|
|
// join all consumers
|
|
for ( int i = 0; i < consumers.size() ; i++ )
|
|
{
|
|
consumers[i].join();
|
|
}
|
|
}
|
|
|
|
|
|
private:
|
|
// Implementations for producers and consumers
|
|
void static producer( SharedQueue<int>& q, const int id, int max_t, int max_n );
|
|
void static consumer( SharedQueue<int>& q, const int id, int max_t = 2000, int max_n = 10 );
|
|
|
|
// Disallow copying for now
|
|
ThreadPool( const ThreadPool& tp );
|
|
|
|
// Consumer and Producers threads
|
|
std::vector<std::thread> consumers;
|
|
std::vector<std::thread> producers;
|
|
|
|
// queue
|
|
SharedQueue<int> q;
|
|
};
|
|
#endif
|