Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added getter for the number of workers and default constructor #9

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions ThreadPool.h
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@
#include <future>
#include <functional>
#include <stdexcept>
#include <algorithm>

class ThreadPool {
public:
ThreadPool(size_t);
ThreadPool();
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
size_t noWorkers() const;
~ThreadPool();
private:
// need to keep track of threads so we can join them
Expand Down Expand Up @@ -54,6 +57,11 @@ inline ThreadPool::ThreadPool(size_t threads)
);
}

// the default number of workers is given by max(1, std::thread::hardware_concurrency())
inline ThreadPool::ThreadPool() : ThreadPool(std::max(1u, std::thread::hardware_concurrency()))
{
}

// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
Expand All @@ -78,6 +86,12 @@ auto ThreadPool::enqueue(F&& f, Args&&... args)
return res;
}

// it may be useful to retrieve the number of workers at runtime
inline size_t ThreadPool::noWorkers() const
{
return workers.size();
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
Expand Down
4 changes: 3 additions & 1 deletion example.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
int main()
{

ThreadPool pool(4);
ThreadPool pool;
std::vector< std::future<int> > results;

std::cout << "Number of workers: " << pool.noWorkers() << std::endl;

for(int i = 0; i < 8; ++i) {
results.push_back(
Expand Down