C++11的异步调用


用C++11的线程库完成异步调用非常方便,标准库提供了非常漂亮的接口。下面就是个很好的例子.

template<typename>
struct async_call;

template<typename R, typename... Args>
struct async_call<R(Args...)>
{
	template<typename F>
	async_call(F&& f, Args... args)
	{
		std::packaged_task<R(Args...)> task(f);
		m_future=task.get_future();
		std::thread(std::move(task), args...).detach();
	}
	
	R get()
	{
		return m_future.get();
	}

private:
	std::future<R> m_future;
};

这个模版类简单地包装了一下标准库,这样调用:

	int a=10, b=20;
	//需要异步执行的代码和参数
	async_call<int(int)> ac([](int x){ return x*x; }, a);
	//串行执行的代码
	b*=b;
	//合并计算结果,并输出
	cout<<ac.get()+b<<endl;

这样基本不用关心线程编程的细节,编程感受也和脚本类似了,哈哈。



以下是一个使用C++线程池进行异步调用的示例: ```cpp #include <iostream> #include <thread> #include <functional> #include <vector> #include <queue> #include <mutex> #include <condition_variable> class ThreadPool { public: ThreadPool(size_t numThreads) : stop(false) { for (size_t i = 0; i < numThreads; ++i) { threads.emplace_back([this] { while (true) { std::function<void()> task; { std::unique_lock<std::mutex> lock(queueMutex); condition.wait(lock, [this] { return stop || !tasks.empty(); }); if (stop && tasks.empty()) { return; } task = std::move(tasks.front()); tasks.pop(); } task(); } }); } } template<class F, class... Args> void enqueue(F&& f, Args&&... args) { { std::unique_lock<std::mutex> lock(queueMutex); tasks.emplace([=] { std::invoke(f, args...); }); } condition.notify_one(); } ~ThreadPool() { { std::unique_lock<std::mutex> lock(queueMutex); stop = true; } condition.notify_all(); for (std::thread& thread : threads) { thread.join(); } } private: std::vector<std::thread> threads; std::queue<std::function<void()>> tasks; std::mutex queueMutex; std::condition_variable condition; bool stop; }; // 示例任务函数 void printHello(int id) { std::cout << "Hello from thread " << id << std::endl; } int main() { ThreadPool pool(4); // 创建一个拥有4个线程线程池 // 向线程池中添加任务 for (int i = 0; i < 10; ++i) { pool.enqueue(printHello, i); } // 等待所有任务完成 // 这里不需要使用pthread_join函数线程池会自动处理任务的执行和完成 // 当线程池析构时,会等待所有任务完成后再退出 // 所以在这里不需要显式地调用join函数 // 但是需要注意的是,如果在线程池析构前没有等待所有任务完成,可能会导致任务被中断 // 所以在实际使用中,需要根据具体情况来决定何时销毁线程池 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值