您好,登錄后才能下訂單哦!
設(shè)計(jì)一個(gè)線程池在Linux環(huán)境下使用C++進(jìn)行多線程編程是一個(gè)常見(jiàn)的任務(wù)。線程池可以幫助你有效地管理線程,避免頻繁地創(chuàng)建和銷毀線程帶來(lái)的開(kāi)銷,同時(shí)提高系統(tǒng)的響應(yīng)性和資源利用率。以下是一個(gè)基本的線程池設(shè)計(jì)思路:
首先,定義一個(gè)線程池類,包含以下主要成員變量:
max_threads
: 最大線程數(shù)min_threads
: 最小線程數(shù)current_threads
: 當(dāng)前活躍線程數(shù)work_queue
: 任務(wù)隊(duì)列threads
: 存儲(chǔ)線程的容器condition_var
: 用于線程同步的條件變量mutex
: 用于保護(hù)共享資源的互斥鎖#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
class ThreadPool {
public:
ThreadPool(size_t min_threads, size_t max_threads);
~ThreadPool();
template<typename F, typename... Args>
std::future<typename std::result_of<F(Args...)>::type> enqueue(F&& f, Args&&... args);
private:
void worker_thread();
void wait_for_available_threads();
void adjust_thread_count();
size_t max_threads_;
size_t min_threads_;
size_t current_threads_;
std::queue<std::packaged_task<void()>> work_queue_;
std::vector<std::thread> threads_;
std::mutex mutex_;
std::condition_variable condition_var_;
};
構(gòu)造函數(shù)初始化線程池,設(shè)置最小和最大線程數(shù)。析構(gòu)函數(shù)確保所有線程在對(duì)象銷毀時(shí)正確退出。
ThreadPool::ThreadPool(size_t min_threads, size_t max_threads)
: max_threads_(max_threads), min_threads_(min_threads), current_threads_(0) {
for (size_t i = 0; i < min_threads; ++i) {
worker_thread();
}
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mutex_);
stop_ = true;
}
condition_var_.notify_all();
for (auto& thread : threads_) {
if (thread.joinable()) {
thread.join();
}
}
}
每個(gè)工作線程運(yùn)行worker_thread
函數(shù),從任務(wù)隊(duì)列中取出任務(wù)并執(zhí)行。
void ThreadPool::worker_thread() {
while (true) {
std::packaged_task<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
condition_var_.wait(lock, [this] { return stop_ || !work_queue_.empty(); });
if (stop_ && work_queue_.empty()) {
break;
}
task = std::move(work_queue_.front());
work_queue_.pop();
}
task();
adjust_thread_count();
}
}
adjust_thread_count
函數(shù)根據(jù)當(dāng)前活躍線程數(shù)和任務(wù)隊(duì)列的狀態(tài)調(diào)整線程數(shù)。
void ThreadPool::adjust_thread_count() {
size_t available_threads = max_threads_ - current_threads_;
while (available_threads > 0 && !work_queue_.empty()) {
worker_thread();
--available_threads;
}
while (current_threads_ < min_threads_ && !work_queue_.empty()) {
worker_thread();
++current_threads_;
}
}
enqueue
函數(shù)將任務(wù)添加到任務(wù)隊(duì)列中,并通知一個(gè)等待的線程來(lái)執(zhí)行該任務(wù)。
template<typename F, typename... Args>
std::future<typename std::result_of<F(Args...)>::type> ThreadPool::enqueue(F&& f, Args&&... args) {
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("enqueue on stopped ThreadPool");
}
work_queue_.push(*task);
}
condition_var_.notify_one();
return result;
}
以下是一個(gè)簡(jiǎn)單的使用示例,展示了如何創(chuàng)建一個(gè)線程池并提交任務(wù)。
#include <iostream>
#include <future>
void task(int id) {
std::cout << "Task " << id << " started" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Task " << id << " finished" << std::endl;
}
int main() {
ThreadPool pool(2, 5);
std::vector<std::future<void>> results;
for (int i = 0; i < 10; ++i) {
results.push_back(pool.enqueue(task, i));
}
for (auto& result : results) {
result.wait();
}
return 0;
}
這個(gè)示例創(chuàng)建了一個(gè)包含2個(gè)最小線程和5個(gè)最大線程的線程池,并提交了10個(gè)任務(wù)。線程池會(huì)自動(dòng)管理線程的創(chuàng)建和銷毀,確保任務(wù)能夠高效地執(zhí)行。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。