Partilhar via


Passo a passo: Implementando futuros

Este tópico mostra como implementar futuros em seu aplicativo. O tópico demonstra como combinar a funcionalidade existente no Concurrency Runtime em algo que faz mais.

Importante

Este tópico ilustra o conceito de futuros para fins de demonstração. Recomendamos que você use std::future ou concurrency::task quando precisar de uma tarefa assíncrona que calcule um valor para uso posterior.

Uma tarefa é um cálculo que pode ser decomposto em cálculos adicionais, mais refinados. Um futuro é uma tarefa assíncrona que calcula um valor para uso posterior.

Para implementar futuros, este tópico define a classe async_future. A async_future classe usa esses componentes do Concurrency Runtime: a classe concurrency::task_group e a classe concurrency::single_assignment . A async_future classe usa a task_group classe para calcular um valor de forma assíncrona e a single_assignment classe para armazenar o resultado da computação. O construtor da classe async_future utiliza uma função de trabalho que calcula o resultado, e o método get recupera o resultado.

Para implementar a classe async_future

  1. Declare uma classe de modelo chamada async_future que é parametrizada no tipo de computação resultante. Adicione public e private seções a esta classe.
template <typename T>
class async_future
{
public:
private:
};
  1. private Na seção da async_future classe, declare um task_group e um single_assignment membro de dados.
// Executes the asynchronous work function.
task_group _tasks;

// Stores the result of the asynchronous work function.
single_assignment<T> _value;
  1. Na classe public, na seção async_future, implemente o construtor. O construtor é um modelo que é parametrizado na função de trabalho que calcula o resultado. O construtor executa assincronamente a função de trabalho no task_group membro de dados e usa a função concurrency::send para gravar o resultado no single_assignment membro de dados.
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());
    });
}
  1. Na public seção da classe async_future, implemente o destrutor. O destruidor aguarda a conclusão da tarefa.
~async_future()
{
   // Wait for the task to finish.
   _tasks.wait();
}
  1. public Na seção da async_future classe, implemente o get método. Este método usa a função concurrency::receive para recuperar o resultado da função de trabalho.
// 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); 
}

Exemplo

Descrição

O exemplo a seguir mostra a classe completa async_future e um exemplo de seu uso. A wmain função cria um objeto std::vetor que contém 10.000 valores inteiros aleatórios. Em seguida, ele usa async_future objetos para localizar os menores e maiores valores contidos no vector objeto.

Código

// 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;
}

Observações

Este exemplo produz a seguinte saída:

smallest: 0
largest:  9999
average:  4981

O exemplo usa o async_future::get método para recuperar os resultados da computação. O async_future::get método aguarda a conclusão do cálculo se o cálculo ainda estiver ativo.

Programação robusta

Para estender a async_future classe para manipular exceções lançadas pela função de trabalho, modifique o async_future::get método para chamar o método concurrency::task_group::wait . O task_group::wait método lança quaisquer exceções que foram geradas pela função de trabalho.

O exemplo a seguir mostra a versão modificada da async_future classe. A wmain função usa um try-catch bloco para imprimir o async_future resultado do objeto ou para imprimir o valor da exceção que é gerada pela função de trabalho.

// 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;
   }
}

Este exemplo produz a seguinte saída:

caught exception: error

Para obter mais informações sobre o modelo de tratamento de exceções no Concurrency Runtime, consulte Tratamento de exceções.

Compilando o código

Copie o código de exemplo e cole-o em um projeto do Visual Studio ou cole-o em um arquivo chamado futures.cpp e, em seguida, execute o seguinte comando em uma janela do prompt de comando do Visual Studio.

cl.exe /EHsc futures.cpp

Ver também

Passo a passo do Concurrency Runtime
Tratamento de exceções
task_group Classe
Classe de Atribuição Única