对于初学者而言,“以多线程运行程序”的最佳起点就是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();
}