Como usar tratamento de exceções para parar um loop paralelo

Este tópico mostra como escrever um algoritmo de pesquisa para uma estrutura de árvore básica.

O tópico Cancelamento explica a função de cancelamento na Biblioteca de Padrões Paralelos. O uso do tratamento de exceções é um modo menos eficiente de cancelar o trabalho paralelo do que o uso dos métodos concurrency::task_group::cancel e concurrency::structured_task_group::cancel. No entanto, um cenário em que o uso da manipulação de exceções para cancelar o trabalho é apropriado é quando você chama uma biblioteca de terceiros que usa tarefas ou algoritmos paralelos, mas não fornece um objeto task_group ou structured_task_group para cancelar.

Exemplo: tipo de árvore básico

O exemplo a seguir mostra um tipo tree básico que contém um elemento de dados e uma lista de nós filho. A seção a seguir mostra o corpo do método for_all, que executa recursivamente uma função de trabalho em cada nó filho.

// A simple tree structure that has multiple child nodes.
template <typename T>
class tree
{
public:
   explicit tree(T data)
      : _data(data)
   {
   }

   // Retrieves the data element for the node. 
   T get_data() const
   {
      return _data;
   }

   // Adds a child node to the tree.
   void add_child(tree& child)
   {
      _children.push_back(child);
   }

   // Performs the given work function on the data element of the tree and
   // on each child.
   template<class Function>
   void for_all(Function& action);

private:
   // The data for this node.
   T _data;
   // The child nodes.
   list<tree> _children;
};

Exemplo: executar o trabalho em paralelo

O exemplo a seguir mostra o método for_all. Ele usa o algoritmo concurrency::parallel_for_each para executar uma função de trabalho em cada nó da árvore em paralelo.

// Performs the given work function on the data element of the tree and
// on each child.
template<class Function>
void for_all(Function& action)
{
   // Perform the action on each child.
   parallel_for_each(begin(_children), end(_children), [&](tree& child) {
      child.for_all(action);
   });

   // Perform the action on this node.
   action(*this);
}

Exemplo: pesquisar um valor na árvore

O exemplo a seguir mostra a função search_for_value, que pesquisa um valor no objeto tree fornecido. Essa função passa para o método for_all uma função de trabalho que é gerada quando encontra um nó de árvore que contém o valor fornecido.

Suponha que a classe tree seja fornecida por uma biblioteca de terceiros e que você não possa modificá-la. Nesse caso, o uso do tratamento de exceções é apropriado porque o método for_all não fornece um objeto task_group ou structured_task_group ao chamador. Portanto, a função de trabalho não pode cancelar diretamente seu grupo de tarefas pai.

Quando a função de trabalho que você fornece a um grupo de tarefas gera uma exceção, o runtime interrompe todas as tarefas que estão no grupo de tarefas (incluindo todos os grupos de tarefas filho) e descarta todas as tarefas que ainda não foram iniciadas. A função search_for_value usa um bloco try-catch para capturar a exceção e imprimir o resultado no console.

// Searches for a value in the provided tree object.
template <typename T>
void search_for_value(tree<T>& t, int value)
{
   try
   {
      // Call the for_all method to search for a value. The work function
      // throws an exception when it finds the value.
      t.for_all([value](const tree<T>& node) {
         if (node.get_data() == value)
         {
            throw &node;
         }
      });
   }
   catch (const tree<T>* node)
   {
      // A matching node was found. Print a message to the console.
      wstringstream ss;
      ss << L"Found a node with value " << value << L'.' << endl;
      wcout << ss.str();
      return;
   }

   // A matching node was not found. Print a message to the console.
   wstringstream ss;
   ss << L"Did not find node with value " << value << L'.' << endl;
   wcout << ss.str();   
}

Exemplo: criar e pesquisar uma árvore em paralelo

O exemplo a seguir cria um objeto tree e pesquisa diversos valores em paralelo. A função build_tree é mostrada posteriormente neste tópico.

int wmain()
{  
   // Build a tree that is four levels deep with the initial level 
   // having three children. The value of each node is a random number.
   mt19937 gen(38);
   tree<int> t = build_tree<int>(4, 3, [&gen]{ return gen()%100000; });

   // Search for a few values in the tree in parallel.
   parallel_invoke(
      [&t] { search_for_value(t, 86131); },
      [&t] { search_for_value(t, 17522); },
      [&t] { search_for_value(t, 32614); }
   );
}

Este exemplo usa o algoritmo concurrency::parallel_invoke para pesquisar valores em paralelo. Para mais informações sobre algoritmos paralelos, confira Algoritmos paralelos.

Exemplo: exemplo de código de tratamento de exceção concluído

O exemplo completo a seguir usa tratamento de exceção para pesquisar valores em uma estrutura de árvore básica.

// task-tree-search.cpp
// compile with: /EHsc
#include <ppl.h>
#include <list>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <random>

using namespace concurrency;
using namespace std;

// A simple tree structure that has multiple child nodes.
template <typename T>
class tree
{
public:
   explicit tree(T data)
      : _data(data)
   {
   }

   // Retrieves the data element for the node. 
   T get_data() const
   {
      return _data;
   }

   // Adds a child node to the tree.
   void add_child(tree& child)
   {
      _children.push_back(child);
   }

   // Performs the given work function on the data element of the tree and
   // on each child.
   template<class Function>
   void for_all(Function& action)
   {
      // Perform the action on each child.
      parallel_for_each(begin(_children), end(_children), [&](tree& child) {
         child.for_all(action);
      });

      // Perform the action on this node.
      action(*this);
   }

private:
   // The data for this node.
   T _data;
   // The child nodes.
   list<tree> _children;
};

// Builds a tree with the given depth. 
// Each node of the tree is initialized with the provided generator function.
// Each level of the tree has one more child than the previous level.
template <typename T, class Generator>
tree<T> build_tree(int depth, int child_count, Generator& g)
{
   // Create the tree node.
   tree<T> t(g());

   // Add children.
   if (depth > 0)
   {
      for(int i = 0; i < child_count; ++i)
      {
         t.add_child(build_tree<T>(depth - 1, child_count + 1, g));
      }
   }

   return t;
}

// Searches for a value in the provided tree object.
template <typename T>
void search_for_value(tree<T>& t, int value)
{
   try
   {
      // Call the for_all method to search for a value. The work function
      // throws an exception when it finds the value.
      t.for_all([value](const tree<T>& node) {
         if (node.get_data() == value)
         {
            throw &node;
         }
      });
   }
   catch (const tree<T>* node)
   {
      // A matching node was found. Print a message to the console.
      wstringstream ss;
      ss << L"Found a node with value " << value << L'.' << endl;
      wcout << ss.str();
      return;
   }

   // A matching node was not found. Print a message to the console.
   wstringstream ss;
   ss << L"Did not find node with value " << value << L'.' << endl;
   wcout << ss.str();   
}

int wmain()
{  
   // Build a tree that is four levels deep with the initial level 
   // having three children. The value of each node is a random number.
   mt19937 gen(38);
   tree<int> t = build_tree<int>(4, 3, [&gen]{ return gen()%100000; });

   // Search for a few values in the tree in parallel.
   parallel_invoke(
      [&t] { search_for_value(t, 86131); },
      [&t] { search_for_value(t, 17522); },
      [&t] { search_for_value(t, 32614); }
   );
}

Este exemplo gera a saída de amostra a seguir.

Found a node with value 32614.
Found a node with value 86131.
Did not find node with value 17522.

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 task-tree-search.cpp e execute o comando a seguir em uma janela do Prompt de comando do Visual Studio.

cl.exe /EHsc task-tree-search.cpp

Confira também

Cancelamento no PPL
Tratamento de exceção
Paralelismo de tarefas
Algoritmos paralelos
Classe task_group
Classe structured_task_group
Função parallel_for_each