I am trying to learn std::threads from C++11 to make a threading system.
I was wondering if there is a way to stop a thread from running (N
Maybe this thread_pool will help you:
#include
#include
#include
using namespace boost;
using namespace boost::phoenix::arg_names;
boost::atomic_size_t counter(0ul);
class thread_pool
{
private:
mutex mx;
condition_variable cv;
typedef function job_t;
std::deque _queue;
thread_group pool;
boost::atomic_bool shutdown;
static void worker_thread(thread_pool& q)
{
while (optional job = q.dequeue())
(*job)();
}
public:
thread_pool() : shutdown(false) {
for (unsigned i = 0; i < boost::thread::hardware_concurrency(); ++i)
pool.create_thread(bind(worker_thread, ref(*this)));
}
void enqueue(job_t job)
{
lock_guard lk(mx);
_queue.push_back(job);
cv.notify_one();
}
optional dequeue()
{
unique_lock lk(mx);
namespace phx = boost::phoenix;
cv.wait(lk, phx::ref(shutdown) || !phx::empty(phx::ref(_queue)));
if (_queue.empty())
return none;
job_t job = _queue.front();
_queue.pop_front();
return job;
}
~thread_pool()
{
shutdown = true;
{
lock_guard lk(mx);
cv.notify_all();
}
pool.join_all();
}
};
Example of use: live On Coliru