progschj / ThreadPool

A simple C++11 Thread Pool implementation
zlib License
7.86k stars 2.24k forks source link

Simplified enqueue #4

Closed ltwardus closed 11 years ago

ltwardus commented 11 years ago

I've simplified the enqueue method, now the additional classes are not needed and the container is std::deque<std::function<void()>>:

template<class Result, class Callable>
std::future<Result> ThreadPoolManager::enqueue(Callable callable) {
  /**
   * Create task, we use RAII here and copy-capture lambda later as this std::packed_task has to be
   * deleted after it was executed.
   */
  auto task = std::make_shared<std::packaged_task<Result()>>(callable);

  /** Get the result of the task */
  std::future<Result> result = task->get_future();

  {
    /** Lock the queue */
    std::unique_lock<Mutex> lock(mutex_);

    /** Push new task to the queue */
    tasks_.push_back([=] {
      /** Execute task */
      (*task)();
    });
  }
  /** Notify one worker that there is a work to do */
  conditional_variable_.notify_one();

  return result;
}
progschj commented 11 years ago

I like this. If only there was a way to move-capture then one could even avoid the shared_ptr.

ltwardus commented 11 years ago

Well, i was messing with something like:

  std::packaged_task<Result()> task(callable);

  ...

  tasks_.push_back(std::bind([](std::packaged_task<Result()> &&task){task();}, std::move(task)));

...

, but with no luck and at the moment it already looks too weird and in my opinion is complicating things more than it's needed :)