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 exemplo mostra como usar o cancelamento para implementar um algoritmo de pesquisa paralela básico.
Exemplo
O exemplo a seguir usa cancelamento para procurar um elemento em uma matriz. A parallel_find_any
função usa o algoritmo concurrency::parallel_for e a função concurrency::run_with_cancellation_token para procurar a posição que contém o valor dado. Quando o loop paralelo encontra o valor, ele chama o método concurrency::cancellation_token_source::cancel para cancelar trabalhos futuros.
// parallel-array-search.cpp
// compile with: /EHsc
#include <ppl.h>
#include <iostream>
#include <random>
using namespace concurrency;
using namespace std;
// Returns the position in the provided array that contains the given value,
// or -1 if the value is not in the array.
template<typename T>
int parallel_find_any(const T a[], size_t count, const T& what)
{
// The position of the element in the array.
// The default value, -1, indicates that the element is not in the array.
int position = -1;
// Call parallel_for in the context of a cancellation token to search for the element.
cancellation_token_source cts;
run_with_cancellation_token([count, what, &a, &position, &cts]()
{
parallel_for(std::size_t(0), count, [what, &a, &position, &cts](int n) {
if (a[n] == what)
{
// Set the return value and cancel the remaining tasks.
position = n;
cts.cancel();
}
});
}, cts.get_token());
return position;
}
int wmain()
{
const size_t count = 10000;
int values[count];
// Fill the array with random values.
mt19937 gen(34);
for (size_t i = 0; i < count; ++i)
{
values[i] = gen()%10000;
}
// Search for any position in the array that contains value 3123.
const int what = 3123;
int position = parallel_find_any(values, count, what);
if (position >= 0)
{
wcout << what << L" is at position " << position << L'.' << endl;
}
else
{
wcout << what << L" is not in the array." << endl;
}
}
/* Sample output:
3123 is at position 7835.
*/
O algoritmo concurrency::parallel_for atua concurrentemente. Portanto, ele não executa as operações em uma ordem pré-determinada. Se a matriz contiver várias instâncias do valor, o resultado pode ser qualquer uma de suas posiçõ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 parallel-array-search.cpp
e, em seguida, execute o seguinte comando em uma janela do prompt de comando do Visual Studio.
cl.exe /EHsc parallel-array-search.cpp
Ver também
Cancelamento no PPL
Algoritmos paralelos
Função parallel_for
cancellation_token_source Classe