From 599b73b21647e6ef2f9fdb3b0a3eef5a1318ec30 Mon Sep 17 00:00:00 2001 From: Eric Teunis de Boone Date: Wed, 8 Jul 2020 16:53:53 +0200 Subject: [PATCH] Ex10: initial header files --- ex10/shared_queue.hh | 18 ++++++++++++ ex10/threadpool.hh | 66 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 ex10/shared_queue.hh create mode 100644 ex10/threadpool.hh diff --git a/ex10/shared_queue.hh b/ex10/shared_queue.hh new file mode 100644 index 0000000..4ba5ff9 --- /dev/null +++ b/ex10/shared_queue.hh @@ -0,0 +1,18 @@ +// Shared_Queue.hh +#include +#include +#include + +#ifndef SHARED_QUEUE_HH +#define SHARED_QUEUE_HH +template +class SharedQueue +{ + // Queue + std::queue queue; + + // Synchronisation + std::mutex mutex; + std::condition_variable cv; +}; +#endif diff --git a/ex10/threadpool.hh b/ex10/threadpool.hh new file mode 100644 index 0000000..c47ccb6 --- /dev/null +++ b/ex10/threadpool.hh @@ -0,0 +1,66 @@ +// ThreadPool.hh +#include "shared_queue.hh" + +#include +#include + +#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& q, const int id, int max_t, int max_n ); + void static consumer( SharedQueue& 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 consumers; + std::vector producers; + + // queue + SharedQueue q; +}; +#endif