1
0
Fork 0

Ex10: initial header files

This commit is contained in:
Eric Teunis de Boone 2020-07-08 16:53:53 +02:00
parent 817e492ef0
commit 599b73b216
2 changed files with 84 additions and 0 deletions

18
ex10/shared_queue.hh Normal file
View file

@ -0,0 +1,18 @@
// Shared_Queue.hh
#include <condition_variable>
#include <mutex>
#include <queue>
#ifndef SHARED_QUEUE_HH
#define SHARED_QUEUE_HH
template <class T>
class SharedQueue
{
// Queue
std::queue<T> queue;
// Synchronisation
std::mutex mutex;
std::condition_variable cv;
};
#endif

66
ex10/threadpool.hh Normal file
View file

@ -0,0 +1,66 @@
// 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