Biblioteca de padrões paralelos (PPL)Parallel Patterns Library (PPL)
A PPL (Parallel Patterns Library) fornece um modelo de programação imperativo que promove a escalabilidade e a facilidade de uso para o desenvolvimento de aplicativos simultâneos.The Parallel Patterns Library (PPL) provides an imperative programming model that promotes scalability and ease-of-use for developing concurrent applications. A PPL baseia-se nos componentes de agendamento e gerenciamento de recursos do Tempo de Execução de Simultaneidade.The PPL builds on the scheduling and resource management components of the Concurrency Runtime. Ele gera o nível de abstração entre o código do aplicativo e o mecanismo de Threading subjacente fornecendo algoritmos genéricos, de tipo seguro e contêineres que agem em dados em paralelo.It raises the level of abstraction between your application code and the underlying threading mechanism by providing generic, type-safe algorithms and containers that act on data in parallel. A PPL também permite desenvolver aplicativos que são dimensionados fornecendo alternativas ao estado compartilhado.The PPL also lets you develop applications that scale by providing alternatives to shared state.
A PPL fornece os seguintes recursos:The PPL provides the following features:
Paralelismo de tarefas: um mecanismo que funciona na parte superior do ThreadPool do Windows para executar vários itens de trabalho (tarefas) em paraleloTask Parallelism: a mechanism that works on top of the Windows ThreadPool to execute several work items (tasks) in parallel
Algoritmos paralelos: algoritmos genéricos que funcionam sobre o tempo de execução de simultaneidade para agir em coleções de dados em paraleloParallel algorithms: generic algorithms that works on top of the Concurrency Runtime to act on collections of data in parallel
Contêineres e objetos paralelos: tipos de contêiner genéricos que fornecem acesso simultâneo seguro aos seus elementosParallel containers and objects: generic container types that provide safe concurrent access to their elements
ExemploExample
A PPL fornece um modelo de programação que se assemelha à biblioteca padrão do C++.The PPL provides a programming model that resembles the C++ Standard Library. O exemplo a seguir demonstra muitos recursos da PPL.The following example demonstrates many features of the PPL. Ele computa vários números Fibonacci em série e em paralelo.It computes several Fibonacci numbers serially and in parallel. Ambos os cálculos atuam em um objeto std:: array .Both computations act on a std::array object. O exemplo também imprime no console o tempo necessário para executar os dois cálculos.The example also prints to the console the time that is required to perform both computations.
A versão serial usa o algoritmo std:: for_each da biblioteca padrão C++ para atravessar a matriz e armazena os resultados em um objeto std:: vector .The serial version uses the C++ Standard Library std::for_each algorithm to traverse the array and stores the results in a std::vector object. A versão paralela executa a mesma tarefa, mas usa o algoritmo de simultaneidade da PPL::p arallel_for_each e armazena os resultados em um objeto concurrency:: concurrent_vector .The parallel version performs the same task, but uses the PPL concurrency::parallel_for_each algorithm and stores the results in a concurrency::concurrent_vector object. A concurrent_vector
classe permite que cada iteração de loop adicione elementos simultaneamente sem a necessidade de sincronizar o acesso de gravação ao contêiner.The concurrent_vector
class enables each loop iteration to concurrently add elements without the requirement to synchronize write access to the container.
Como o parallel_for_each
age simultaneamente, a versão paralela deste exemplo deve classificar o concurrent_vector
objeto para produzir os mesmos resultados que a versão serial.Because parallel_for_each
acts concurrently, the parallel version of this example must sort the concurrent_vector
object to produce the same results as the serial version.
Observe que o exemplo usa um método simples para calcular os números de Fibonacci; no entanto, esse método ilustra como o Tempo de Execução de Simultaneidade pode melhorar o desempenho de cálculos longos.Note that the example uses a naïve method to compute the Fibonacci numbers; however, this method illustrates how the Concurrency Runtime can improve the performance of long computations.
// parallel-fibonacci.cpp
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <concurrent_vector.h>
#include <array>
#include <vector>
#include <tuple>
#include <algorithm>
#include <iostream>
using namespace concurrency;
using namespace std;
// Calls the provided work function and returns the number of milliseconds
// that it takes to call that function.
template <class Function>
__int64 time_call(Function&& f)
{
__int64 begin = GetTickCount();
f();
return GetTickCount() - begin;
}
// Computes the nth Fibonacci number.
int fibonacci(int n)
{
if(n < 2)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
int wmain()
{
__int64 elapsed;
// An array of Fibonacci numbers to compute.
array<int, 4> a = { 24, 26, 41, 42 };
// The results of the serial computation.
vector<tuple<int,int>> results1;
// The results of the parallel computation.
concurrent_vector<tuple<int,int>> results2;
// Use the for_each algorithm to compute the results serially.
elapsed = time_call([&]
{
for_each (begin(a), end(a), [&](int n) {
results1.push_back(make_tuple(n, fibonacci(n)));
});
});
wcout << L"serial time: " << elapsed << L" ms" << endl;
// Use the parallel_for_each algorithm to perform the same task.
elapsed = time_call([&]
{
parallel_for_each (begin(a), end(a), [&](int n) {
results2.push_back(make_tuple(n, fibonacci(n)));
});
// Because parallel_for_each acts concurrently, the results do not
// have a pre-determined order. Sort the concurrent_vector object
// so that the results match the serial version.
sort(begin(results2), end(results2));
});
wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;
// Print the results.
for_each (begin(results2), end(results2), [](tuple<int,int>& pair) {
wcout << L"fib(" << get<0>(pair) << L"): " << get<1>(pair) << endl;
});
}
A saída de exemplo a seguir é para um computador com quatro processadores.The following sample output is for a computer that has four processors.
serial time: 9250 ms
parallel time: 5726 ms
fib(24): 46368
fib(26): 121393
fib(41): 165580141
fib(42): 267914296
Cada iteração do loop requer uma quantidade de tempo diferente para ser concluída.Each iteration of the loop requires a different amount of time to finish. O desempenho do parallel_for_each
é limitado pela operação que é concluída por último.The performance of parallel_for_each
is bounded by the operation that finishes last. Portanto, você não deve esperar melhorias de desempenho lineares entre as versões serial e paralelas deste exemplo.Therefore, you should not expect linear performance improvements between the serial and parallel versions of this example.
Tópicos RelacionadosRelated Topics
TítuloTitle | DescriçãoDescription |
---|---|
Paralelismo de TarefasTask Parallelism | Descreve a função de tarefas e grupos de tarefas na PPL.Describes the role of tasks and task groups in the PPL. |
Algoritmos paralelosParallel Algorithms | Descreve como usar algoritmos paralelos, como parallel_for e parallel_for_each .Describes how to use parallel algorithms such as parallel_for and parallel_for_each . |
Contêineres e objetos paralelosParallel Containers and Objects | Descreve os vários contêineres paralelos e objetos que são fornecidos pela PPL.Describes the various parallel containers and objects that are provided by the PPL. |
Cancelamento no PPLCancellation in the PPL | Explica como cancelar o trabalho que está sendo executado por um algoritmo paralelo.Explains how to cancel the work that is being performed by a parallel algorithm. |
Runtime de SimultaneidadeConcurrency Runtime | Descreve o Tempo de Execução de Simultaneidade, que simplifica a programação paralela e contém links para tópicos relacionados.Describes the Concurrency Runtime, which simplifies parallel programming, and contains links to related topics. |