C++——線程池實例分析

class fixed_thread_pool {
		public:
			explicit fixed_thread_pool(size_t thread_count)
				: data_(std::make_shared<data>()) {
				for (size_t i = 0; i < thread_count; ++i) {
					std::thread([data = data_] {
						std::unique_lock<std::mutex> lk(data->mtx_);
						for (;;) {
							if (!data->tasks_.empty()) {
								auto current = std::move(data->tasks_.front());
								data->tasks_.pop();
								lk.unlock();  //這裏該線程已經拿到了任務,所以解鎖,可以讓其它的線程來獲取任務
								current();
								lk.lock(); //執行到這裏了說明這個線程是空閒的,可以繼續接受其他任務,所以它要去搶到鎖用於執行其他的任務
							}
							else if (data->is_shutdown_) {
								break;
							}
							else {
								data->cond_.wait(lk);
							}
						}
					}).detach();
				}
			}

			fixed_thread_pool() = default;
			fixed_thread_pool(fixed_thread_pool&&) = default;

			~fixed_thread_pool() {
				if ((bool)data_) {
					{
						std::lock_guard<std::mutex> lk(data_->mtx_);
						data_->is_shutdown_ = true;
					}
					data_->cond_.notify_all();
				}
			}

			template <class F>
			void execute(F&& task) {
				{
					std::lock_guard<std::mutex> lk(data_->mtx_);
					data_->tasks_.emplace(std::forward<F>(task));
				}
				data_->cond_.notify_one();
			}

		private:
			struct data {
				std::mutex mtx_;
				std::condition_variable cond_;
				bool is_shutdown_ = false;
				std::queue<std::function<void()>> tasks_;
			};
			std::shared_ptr<data> data_;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章