Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Este tópico mostra como escrever um algoritmo de pesquisa para uma estrutura de árvore básica.
O tópico Cancelamento explica o papel do cancelamento na Biblioteca de Padrões Paralelos. O uso do tratamento de exceções é uma maneira 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 do tratamento 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 task_group ou structured_task_group objeto para cancelar.
Exemplo: Tipo de árvore básica
O exemplo a seguir mostra um tipo básico tree 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 trabalho em paralelo
O exemplo a seguir mostra o for_all método. Ele usa o algoritmo concurrency::parallel_for_each para executar uma função de tarefa 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 search_for_value função, que procura um valor no objeto fornecido tree . Essa função passa para o for_all método uma função de trabalho que é lançada quando encontra um nó de árvore que contém o valor fornecido.
Suponha que a tree classe é fornecida por uma biblioteca de terceiros e que você não pode modificá-la. Nesse caso, o uso do tratamento de exceção é apropriado porque o for_all método não fornece um task_group ou structured_task_group objeto para o chamador. Portanto, a função de trabalho não consegue cancelar diretamente o seu grupo de tarefas principal.
Quando a função de trabalho fornecida a um grupo de tarefas gera uma exceção, o tempo de execução interrompe todas as tarefas que estão nesse grupo de tarefas (incluindo quaisquer grupos de tarefas filho) e descarta todas as tarefas que ainda não foram iniciadas. A search_for_value função usa um try-catch bloco 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 tree objeto e o pesquisa por vários valores em paralelo. A build_tree função é 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 obter mais informações sobre esse algoritmo, consulte Algoritmos paralelos.
Exemplo: Exemplo de código de tratamento de exceção concluído
O exemplo completo a seguir usa o tratamento de exceções para procurar 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 seguinte saída.
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, em seguida, execute o seguinte comando em uma janela do prompt de comando do Visual Studio.
cl.exe /EHsc task-tree-search.cpp
Ver também
Cancelamento no PPL
Tratamento de exceções
Paralelismo de tarefas
Algoritmos paralelos
task_group Classe
structured_task_group Classe
Função parallel_for_each