Návod: Implementace tříd future
Toto téma ukazuje, jak implementovat futures ve vaší aplikaci.Téma ukazuje, jak sloučit existující funkce v modulu Runtime souběžnosti na něco jiného, který neobsahuje více.
Důležité |
---|
Toto téma ukazuje koncept termínů pro demonstrační účely.Doporučujeme používat std::future nebo concurrency::task Pokud požadujete asynchronní úkol, který vypočítá hodnotu pro pozdější použití. |
A úkol je výpočet, který lze rozložit na další, více detailní výpočty.A budoucí je asynchronní úkol, který vypočítá hodnotu pro pozdější použití.
Provádět futures definuje toto téma async_future třídy.async_future Tyto součásti Runtime souběžnosti používá třída: concurrency::task_group třída a concurrency::single_assignment třídy.async_future Třídy používá task_group třídy vypočítat hodnotu asynchronně a single_assignment třídy k ukládání výsledků výpočtu.Konstruktor async_future třída má pracovní funkce, která vypočítá výsledek, a get metoda načte výsledky.
Implementace třídy async_future
Deklarovat třídu šablony s názvem async_future , na typu výpočtu výsledné Parametrizovaná.Přidat public a private oddíly do této třídy.
template <typename T> class async_future { public: private: };
V private část async_future třídy, deklarace task_group a single_assignment datový člen.
// Executes the asynchronous work function. task_group _tasks; // Stores the result of the asynchronous work function. single_assignment<T> _value;
V public sekce async_future třídy, které implementují konstruktoru.Konstruktor je šablona, která je parametrizovaná na pracovní funkce, která vypočítá výsledek.Konstruktor asynchronně vykonává funkci práce v task_group datový člen a používá concurrency::send funkce zapsat výsledek single_assignment datový člen.
template <class Functor> explicit async_future(Functor&& fn) { // Execute the work function in a task group and send the result // to the single_assignment object. _tasks.run([fn, this]() { send(_value, fn()); }); }
V public sekce async_future třídy, které implementují destruktoru.Destruktor čeká na dokončení úlohy.
~async_future() { // Wait for the task to finish. _tasks.wait(); }
V public část async_future třídy, které implementují get metody.Tato metoda používá concurrency::receive funkce načíst výsledek funkce práce.
// Retrieves the result of the work function. // This method blocks if the async_future object is still // computing the value. T get() { return receive(_value); }
Příklad
Description
Následující příklad ukazuje kompletní async_future třídy a příklad jeho využití.wmain Funkce vytvoří std::vector objekt, který obsahuje hodnoty 10 000 náhodné celé číslo.Poté použije async_future objekty, které chcete najít nejnižší a nejvyšší hodnoty, které jsou obsaženy v vector objektu.
Kód
// futures.cpp
// compile with: /EHsc
#include <ppl.h>
#include <agents.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
using namespace concurrency;
using namespace std;
template <typename T>
class async_future
{
public:
template <class Functor>
explicit async_future(Functor&& fn)
{
// Execute the work function in a task group and send the result
// to the single_assignment object.
_tasks.run([fn, this]() {
send(_value, fn());
});
}
~async_future()
{
// Wait for the task to finish.
_tasks.wait();
}
// Retrieves the result of the work function.
// This method blocks if the async_future object is still
// computing the value.
T get()
{
return receive(_value);
}
private:
// Executes the asynchronous work function.
task_group _tasks;
// Stores the result of the asynchronous work function.
single_assignment<T> _value;
};
int wmain()
{
// Create a vector of 10000 integers, where each element
// is between 0 and 9999.
mt19937 gen(2);
vector<int> values(10000);
generate(begin(values), end(values), [&gen]{ return gen()%10000; });
// Create a async_future object that finds the smallest value in the
// vector.
async_future<int> min_value([&]() -> int {
int smallest = INT_MAX;
for_each(begin(values), end(values), [&](int value) {
if (value < smallest)
{
smallest = value;
}
});
return smallest;
});
// Create a async_future object that finds the largest value in the
// vector.
async_future<int> max_value([&]() -> int {
int largest = INT_MIN;
for_each(begin(values), end(values), [&](int value) {
if (value > largest)
{
largest = value;
}
});
return largest;
});
// Calculate the average value of the vector while the async_future objects
// work in the background.
int sum = accumulate(begin(values), end(values), 0);
int average = sum / values.size();
// Print the smallest, largest, and average values.
wcout << L"smallest: " << min_value.get() << endl
<< L"largest: " << max_value.get() << endl
<< L"average: " << average << endl;
}
Komentáře
Tento příklad vytvoří následující výstup:
V příkladu async_future::get metoda načíst výsledky výpočtu.async_future::get Metoda čeká výpočtu dokončit, pokud je výsledkem výpočtu je stále aktivní.
Robustní programování
Rozšířit async_future třídy pro zpracování výjimek, které jsou vyvolány pracovní funkce, změna async_future::get metoda volání concurrency::task_group::wait metody.task_group::wait Metoda vyvolá všechny výjimky, které byly vytvořeny podle pracovních funkcí.
Následující příklad ukazuje upravenou verzi async_future třídy.wmain Funkce používá try-catch blok tisknout výsledek async_future objektu nebo k tisku hodnoty výjimky, která je generována pomocí funkce práce.
// futures-with-eh.cpp
// compile with: /EHsc
#include <ppl.h>
#include <agents.h>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace concurrency;
using namespace std;
template <typename T>
class async_future
{
public:
template <class Functor>
explicit async_future(Functor&& fn)
{
// Execute the work function in a task group and send the result
// to the single_assignment object.
_tasks.run([fn, this]() {
send(_value, fn());
});
}
~async_future()
{
// Wait for the task to finish.
_tasks.wait();
}
// Retrieves the result of the work function.
// This method blocks if the async_future object is still
// computing the value.
T get()
{
// Wait for the task to finish.
// The wait method throws any exceptions that were generated
// by the work function.
_tasks.wait();
// Return the result of the computation.
return receive(_value);
}
private:
// Executes the asynchronous work function.
task_group _tasks;
// Stores the result of the asynchronous work function.
single_assignment<T> _value;
};
int wmain()
{
// For illustration, create a async_future with a work
// function that throws an exception.
async_future<int> f([]() -> int {
throw exception("error");
});
// Try to read from the async_future object.
try
{
int value = f.get();
wcout << L"f contains value: " << value << endl;
}
catch (const exception& e)
{
wcout << L"caught exception: " << e.what() << endl;
}
}
Tento příklad vytvoří následující výstup:
Další informace o modelu zpracování výjimek v modulu Runtime souběžnosti naleznete v tématu Zpracování výjimek v Concurrency Runtime.
Probíhá kompilace kódu
Zkopírovat ukázkový kód a vložit jej do projektu sady Visual Studio nebo vložit do souboru s názvem futures.cpp a potom spusťte následující příkaz v okně Příkazový řádek Visual Studio.
cl.exe /EHsc futures.cpp
Viz také
Referenční dokumentace
Koncepty
Zpracování výjimek v Concurrency Runtime