c++线程–线程池

c++线程–线程池

代码来自:github.com/progschj/ThreadPool
先来看看TheadPool这个类的定义:
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 to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks;

// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};

然后我们再来看一看主函数:


int main()
{
//create four threads and blocking them
ThreadPool pool(4);
std::vector< std::future<int> > results;

for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i]() -> int {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "world " << i << std::endl;
return (i * i);
})
);
}

for (auto && result : results)
std::cout <<"return: "<< result.get() << '\n';
getchar();
return 0;
}

看看TheadPool pool(4)是如何构造4个线程的:


// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for (size_t i = 0; i<threads; ++i)
workers.emplace_back(
[this]
{

//循环(不断从任务队列中取出任务)
for (;;)
{
//void task()
std::function<void()> task;

{
//加锁
std::unique_lock<std::mutex> lock(this->queue_mutex);
//blocking this thread while predicate equal false

//unlock if blocking
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });
//当线程池停止时并且任务队列为空时
if (this->stop && this->tasks.empty())
return;
//取出任务
task = std::move(this->tasks.front());
this->tasks.pop();
}
//执行任务
task();
}
}
);
}

好,现在有4个线程等待任务队列中任务的到来,现在来看一下任务入队函数:


// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(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> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);

// don't allow enqueueing after stopping the pool
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
//将任务加入到任务队列
tasks.emplace([task]() { (*task)(); });
}
//唤醒一个线程
condition.notify_one();
//返回共享状态,调用get函数阻塞直到获得返回值
return res;
}

可以看到主函数中加入了八个任务到任务队列中,每加入一个任务,就会调用condition.notify_one函数来唤醒一个线程,线程从任务队列中取出任务执行。

涉及到的知识:

std::mutex

std::condition_variable

std::future

std::unique_lock

std::make_shared

std::function

std::thread

c++ lambda表达式

One thought on “c++线程–线程池

发表评论

电子邮件地址不会被公开。 必填项已用*标注