#include <iostream> #include <thread> #include <deque> #include <functional> #include…
- User
#include #include #include #include #include #include #include <condition_variable> #include #include #include
class ZYLThreadPool { public: ZYLThreadPool(size_t minThreads = 20, size_t maxThreads = 200) : _minThreads(minThreads) , _maxThreads(maxThreads) , _stop(false) { worker_threads.reserve(_maxThreads); for (size_t i = 0; i < _minThreads; ++i) { create_thread(); } }
codevoid create_thread() { worker_threads.emplace_back([this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->_mutex); this->_condVar.wait(lock, [this] { return this->_stop || !this->_taskQueue.empty(); }); if (this->_stop && this->_taskQueue.empty()) return; task = std::move(this->_taskQueue.front()); this->_taskQueue.pop_front(); } task(); } }); } template <typename F, typename... Args> auto submit(F&& f, Args&&... args)-> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { throw std::runtime_error("Submit on stopped ZYLThreadPool"); } if (_taskQueue.size() >= worker_threads.size() && worker_threads.size() < _maxThreads) { create_thread(); } _taskQueue.emplace_back([task] { (*task)(); }); } _condVar.notify_one(); return result; } void cancel() { std::unique_lock<std::mutex> lock(_mutex); if (!_stop) { _stop = true; _condVar.notify_all(); } for (std::thread& worker : worker_threads) worker.join(); } size_t getNumTasks() { std::unique_lock<std::mutex> lock(_mutex); return _taskQueue.size(); } ~ZYLThreadPool() { cancel(); } - Assistant
在上述代码中,存在以下问题:
- 当_dequeue_packets为空时,你直接使用continue语句,这导致线程会进入死循环,因为没有等待新任务。在这种情况下,为了避免死循环,你需要在这里添加一定的等待时间,例如:
std::this_thread::sleep_for(std::chrono::milliseconds(1));,或者改进一下任务执行逻辑。 - 由于这个问题,任务数不会达到期望的100,因为线程将一直忙于执行这些死循环任务。这也可能导致在任务取消后,你仍然能看到大量活跃的线程。
这是修正后的代码:
cppvoid _task() { std::unique_lock<std::mutex> lock(_mutex); while (_running) { if (_dequeue_packets.empty()) { lock.unlock(); // 添加等待时间,避免死循环 std::this_thread::sleep_for(std::chrono::milliseconds(1)); lock.lock(); continue; } if (!_running) break; double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); std::cout << "running task" << std::endl; lock.lock(); } std::cout<<"End task end,dev:"<<_devid<<std::endl; } - 当_dequeue_packets为空时,你直接使用continue语句,这导致线程会进入死循环,因为没有等待新任务。在这种情况下,为了避免死循环,你需要在这里添加一定的等待时间,例如:
- User
哪怕我加了延时,启动100个任务,期望的任务数和线程数均不是100,而是68,停止后,期望的任务数和线程数均不是预期的数字,请再修改
- Assistant
我明白了,你可能期望线程池在每个任务启动时都尽可能地创建新线程,直到达到最大线程数。这时,只有当线程池已满时,任务会在队列中排队等待执行。
现在,你需要修改一下
submit方法的逻辑。以下是修改后的代码:cpptemplate <typename F, typename... Args> auto submit(F&& f, Args&&... args)-> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { throw std::runtime_error("Submit on stopped ZYLThreadPool"); } if (worker_threads.size() < _maxThreads) { create_thread(); } _taskQueue.emplace_back([task] { (*task)(); }); } _condVar.notify_one(); return result; } - User
不是这个意思,我是想确认,1.启动100个任务,期望的任务数和线程数均不是100,而是68,停止任务后,正在执行的任务数不是0,这个是正常的吗?如果我有新的任务进来,会受影响吗?如果是不正常,请修改,如果正常,就没问题;2.如果是队列非空,每个线程任务的队列出队时间很短的,这也会引起线程会进入死循环吗?有优化方案吗?
- Assistant
-
启动100个任务,由于任务很快就会完成(队列为空),所以实际创建的线程数可能低于100。这是正常的。线程池会在需要时自动调整线程数。当新任务进入线程池时,会根据当前任务队列和线程数来决定是否创建新线程。所以,你没有必要担心新任务的执行会受影响。
-
如果队列非空且出队时间很短,这不会导致死循环。死循环的问题出现在上一个修复中,当_dequeue_packets为空时,线程会不断检查队列并消耗CPU资源。在这种情况下,通过添加等待时间或者使用条件变量等待新任务的到来,可以解决死循环问题。
要优化这个问题,可以修改
Test类中的_task方法,使用条件变量等待新任务到来,而不是使用死循环。这里是修改后的代码:cppclass Test { public: // ...其他代码保持不变 private: std::mutex _mutex; std::condition_variable _condVar; // ... 其他成员变量 void _task() { std::unique_lock<std::mutex> lock(_mutex); while (_running) { _condVar.wait(lock, [this] { return !_running || !_dequeue_packets.empty(); }); if (!_running) break; double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); std::cout << "running task" << std::endl; lock.lock(); } std::cout<<"End task end,dev:"<<_devid<<std::endl; } // ...其他代码保持不变 }; -
- User
条件变量是否会导致阻塞?要求出队的时候不能阻塞的。请把上面优化方案补充完整,并且要求不能阻塞
- Assistant
条件变量的作用是在等待某个条件满足时阻塞线程,直到被通知。这有助于在等待的过程中不消耗不必要的CPU资源。但如果你的要求是不阻塞,一个可能的方法是给每个线程一个微小的等待时间(比如1毫秒)让出CPU,然后再重新检查条件是否满足。这种方法仍会产生一些(较小)的CPU使用,但在某些实际场景下,可以作为一种折衷方案。
这是修改后的代码:
cppvoid _task() { std::unique_lock<std::mutex> lock(_mutex); while (_running) { if (_dequeue_packets.empty()) { lock.unlock(); // 添加等待时间,避免阻塞 std::this_thread::sleep_for(std::chrono::milliseconds(1)); lock.lock(); continue; } double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); std::cout << "running task" << std::endl; lock.lock(); } std::cout<<"End task end,dev:"<<_devid<<std::endl; }这种方法允许任务线程在等待新任务到来时,仅仅等待短暂的时间,然后立即重新检查条件。这将消除阻塞,但仍可能产生一定的CPU占用。