Skip to content

Instantly share code, notes, and snippets.

@jen6
Created January 10, 2016 15:25
Show Gist options
  • Save jen6/d9b9755abb1bb090e0e5 to your computer and use it in GitHub Desktop.
Save jen6/d9b9755abb1bb090e0e5 to your computer and use it in GitHub Desktop.
class thread_pool
{
std::atomic_bool done;
thread_safe_queue<std::function<void()> > work_queue;
std::vector<std::thread> threads;
join_threads joiner;
void worker_thread()
{
while(!done)
{
std::function<void()> task;
if(work_queue.try_pop(task))
{
task();
}
else
{
std::this_thread::yield();
}
}
}
public:
thread_pool():
done(false),joiner(threads)
{
unsigned const thread_count=std::thread::hardware_concurrency();
try
{
for(unsigned i=0;i<thread_count;++i)
{
threads.push_back(
std::thread(&thread_pool::worker_thread,this));
}
}
catch(...)
{
done=true;
throw;
}
}
~thread_pool()
{
done=true;
}
template<typename FunctionType>
void submit(FunctionType f)
{
work_queue.push(std::function<void()>(f));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment