0. 概述
本文将介绍如何使用C++11的标准库进行异步执行函数的封装,涵盖以下几个方面:
- 异步执行阻塞或CPU密集型任务
- 延迟执行函数的实现
- 使用线程池进行任务管理和调度
- 提供立即异步执行函数
really_async
和延迟执行函数delay_call
1. 线程池的封装
1.1 线程池类设计
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <stdexcept>
#include <future>
class ThreadPool {
public:
explicit ThreadPool(size_t threads);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
ThreadPool::ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
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();
}
});
}
}
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);
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task] { (*task)(); });
}
condition.notify_one();
return res;
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
worker.join();
}
class ThreadPoolSingleton {
public:
static ThreadPoolSingleton& instance() {
static ThreadPoolSingleton instance;
return instance;
}
ThreadPool& pool() { return _pool; }
private:
ThreadPoolSingleton() : _pool(10) {}
~ThreadPoolSingleton() = default;
ThreadPool _pool;
};
#endif
1.2 流程图
2. 异步执行函数
#include <functional>
#include <thread>
#include <future>
template <typename Callable, typename... Args>
void really_async(Callable&& f, Args&&... args) {
auto task = std::make_shared<std::packaged_task<void()>>(
std::bind(std::forward<Callable>(f), std::forward<Args>(args)...)
);
#ifdef NOT_USE_THREAD_POOL
std::thread([task]() { (*task)(); }).detach();
#else
auto& pool = ThreadPoolSingleton::instance().pool();
pool.enqueue([task]() { (*task)(); });
#endif
}
2.1流程图
3. 延迟异步执行函数
#include <functional>
#include <thread>
#include <chrono>
template <class Callable, class... Args>
void delay_call(int after, bool async, Callable&& f, Args&&... args) {
auto task = std::make_shared<std::packaged_task<void()>>(
std::bind(std::forward<Callable>(f), std::forward<Args>(args)...)
);
if (async) {
#ifdef NOT_USE_THREAD_POOL
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
(*task)();
}).detach();
#else
auto& pool = ThreadPoolSingleton::instance().pool();
pool.enqueue([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
(*task)();
});
#endif
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
(*task)();
}
}
3.1 流程图
4. 完整代码 call_async.hpp
#pragma once
#include <functional>
#include <chrono>
#include <future>
#include <thread>
// #define NOT_USE_THREAD_POOL
#ifndef NOT_USE_THREAD_POOL
#include "thread_pool.hpp"
#endif
template <typename Callable, typename... Args>
void really_async(Callable&& f, Args&&... args) {
auto task = std::make_shared<std::packaged_task<void()>>(
std::bind(std::forward<Callable>(f), std::forward<Args>(args)...)
);
#ifdef NOT_USE_THREAD_POOL
std::thread([task]() { (*task)(); }).detach();
#else
auto& pool = ThreadPoolSingleton::instance().pool();
pool.enqueue([task]() { (*task)(); });
#endif
}
template <class Callable, class... Args>
void delay_call(int after, bool async, Callable&& f, Args&&... args) {
auto task = std::make_shared<std::packaged_task<void()>>(
std::bind(std::forward<Callable>(f), std::forward<Args>(args)...)
);
if (async) {
#ifdef NOT_USE_THREAD_POOL
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
(*task)();
}).detach();
#else
auto& pool = ThreadPoolSingleton::instance().pool();
pool.enqueue([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
(*task)();
});
#endif
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
(*task)();
}
}