multithreading - construction of thread using lambda expression -
can explain thread created on lambda function below? technique used? can recommend reference understand semantics?
i posted full code now:
class threadpool { public: threadpool(size_t); template<class f, class... args> auto enqueue(f&& f, args&&... args) ->std::future<typename std::result_of<f(args...)>::type>; ~threadpool(); private: // need keep track of threads can join them std::vector< std::thread > workers_m; // task queue std::queue< std::function<void()> > tasks_m; // synchronization std::mutex queue_mutex_m; std::condition_variable condition_m; bool stop_m; }; // constructor launches amount of workers inline threadpool::threadpool(size_t threads) : stop_m(false) { std::thread::id id = std::this_thread::get_id(); (size_t = 0; < threads; ++i) { workers_m.emplace_back( [this] { (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this- >queue_mutex_m); std::thread::id id1 = std::this_thread::get_id(); this->condition_m.wait(lock, [this]{ return this->stop_m || !this->tasks_m.empty(); }); std::thread::id id = std::this_thread::get_id(); if (this->stop_m && this->tasks_m.empty()) return; task = std::move(this->tasks_m.front()); this->tasks_m.pop(); } task(); } } ); } }
threadpools constructor using emplace_back function of std::vector construct std::thread of workers_m variable. emplace_back differs push_back in directly constructs element type forwarding parameters passed constructor of element type (std::thread). push_back, on other hand, requires either lvalue or temporary element type , appropriately copy or move of vector.
threadpool's constructor in loop create appropriate amount of worker threads, specified constructor argument (threads). 1 of std::threads constructors takes callable , number of arguments , run function on corresponding thread. in case, lambda being passed in used construct thread run long necessary (given for(;;) ), acquire mutex grant exclusive access task queue , , use condition variable wait until either stop flag set, or until there available in queue.
once condition variable notified , 1 of 2 conditions true, thread can continue. however, of 2 conditions true not known, hence check
if (this->stop_m && this->tasks_m.empty()) return; which seems bit flawed though, because if stop_m set worker threads should stop processing tasks, if queue still contains tasks do. check fire of both conditions true.
if above check false, thread std::moves task out of queue, pop()s it, , releases mutex held unique_lock due lock's destructor. thread executes task calling it. process repeated, due for(;;) loop
Comments
Post a Comment