I'm interesting what is the purpose of .then construction in PPL and where can I test it? It seems Visual Studio 2012 don't support it yet (may be some future CTP's?). And does it have equivalents in standard C++11 async library?

有帮助吗?

解决方案

The purpose is for you to be able to express asynchronous tasks that have to be executed in sequence.

For example, let's say I'm in a GUI application. When the user presses a button, I want to start a task asynchronously to retrieve a file online, then process it to retrieve some kind of data, then use this data to update the GUI. While this is happening, there are tons of other tasks going on, mainly to keep the GUI responsive.

This can be done by using callbacks that call callbacks. The .then() feature associated with lambdas allows you to write all the callbacks content where you instantiate it (you can still use separate callbacks if you want). It also don't guarantee that the work of each separate task will be done by the same thread, making possible for free threads to steal the tasks if the initial thread have too much work to do already.

The .then() function doesn't exists in C++11 but it is proposed to be added to the std::future class (that is basically a handle to a task or task result).

其他提示

Klaim already made a great answer, but I thought I'd give a specific example.

.then attaches a continuation to the task, and is the async equivalent to the synchronous .get, basically.

C++11 has std::future, which is the equivalent to a concurrency::task. std::future currently only has .get, but there is a proposal to add .then (and other good stuff).

std::async(calculate_answer(the_question_of_everything))
    .then([](std::future<int> f){ std::cout << f.get() << "\n"; });

The above snippet will create an asynchronous task (launched with std::async), and then attach a continuation which gets passed the std::future of the finished task as soon as the aforementioned task is done. This actually returns another std::future for that task, and the current C++11 standard would block on its destructor, but there is another proposal to make the destructor unblocking. So with the above code, you create a fire-and-forget task that prints the answer as soon as it's calculated.

The blocking equivalent would be:

auto f = std::async(calculate_answer(the_question_of_everything));
std::cout << f.get() << "\n";

This code will block in f.get() until the answer becomes available.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top