Multithreading (One)

The following excerpt is from The C++ Standard Library – Second Edition :

For novices, the best starting point to run your program with multiple threads is the high-level interface of the C++ standard library provided by std::async() and class std::future<>:
1. async() provides an interface to let a piece of functionality, a callable object (see Section 4.4, page 54), run in the background as a separate thread, if possible.
2. Class future<> allows you to wait for the thread to be finished and provides access to its outcome: return value or exception, if any.

假设我们需要计算两个操作数的总和,而这两个操作数是两个函数的返回值。寻常做法如下:
func1()+func2()

这意味着对操作数的处理是循序发生的。程序首先调用func1()然后调用func2(),或是颠倒过来(根据语言规则,这一次序无法预期)。不论哪种情况,整体处理时间是func1()所花时间加上func2()所花时间,再加上计算总和所花的时间。
近年来,使用多处理器(multiprocessor)的硬件几乎处处可见,我们因此可以将上述计算做的更好,可以尝试并行运行func1()和func2(),使其整体运行时间只需是”func1()和func2()运行时间中的较大者”加上计算总和的时间。

#include <future>
#include <thread>
#include <chrono>
#include <random>
#include <iostream>
#include <exception>
using namespace std;

int doSomething(char c)
{
	default_random_engine dre(c);
	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('.');
}

int func2()
{
	return doSomething('+');
}

int main()
{
	cout << "starting func1() in background"
		<< "and fun2() in foreground:" << endl;

	future<int> result1(async(func1));

	int result2 = func2();

	int result = result1.get() + result2;

	cout << "\nresult of func1()+func2():" << result
		<< endl;

	return 0;
}

Add a Comment

Your email address will not be published. Required fields are marked *