对于初学者而言,“以多线程运行程序”的最佳起点就是C++标准库中由std::sync()和class std::future<>提供的高级接口:
- async()提供一个接口,让一段功能或者说一个callable object 若是可能的话在后台运行,成为一个独立的线程。
- Class future<>允许你等待线程结束并获取其结果(一个返回值或者一个异常)
下面的这个例子是需要计算两个操作数的和,而这两个数是两个函数的返回值。
// async1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <future>
#include <thread>
#include <chrono>
#include <random>
#include <iostream>
#include <exception>
using namespace std;
int doSomething(char c)
{
//random-number generator(use C as seed to get different sequence)
std::default_random_engine dre(c);
std::uniform_int_distribution<int> id(10,1000);
//每隔一会就循环打印
for (int i = 0; i < 10; ++i) {
this_thread::sleep_for(chrono::milliseconds(id(dre)));
cout.put(c).flush();
}
return c;
}
int func1()
{
return doSomething('.');//这里要记住:func1() 传入的是 点点,点点,点点
}
int func2()
{
return doSomething(

本文介绍了C++标准库中的async()函数用于实现多线程并发执行的功能。通过示例展示了如何使用async()启动异步任务,并通过future<>获取结果。async()确保了函数可能在后台线程执行,而get()用于等待结果或异常,可能造成阻塞。文章讨论了不同情况下async()启动和结束的情况,以及如何避免未调用get()导致的后台任务未执行的问题。
最低0.47元/天 解锁文章
358

被折叠的 条评论
为什么被折叠?



