description | title | ms.date | helpviewer_keywords | ms.assetid | ||
---|---|---|---|---|---|---|
Learn more about: How to: Use Cancellation to Break from a Parallel Loop |
How to: Use Cancellation to Break from a Parallel Loop |
11/04/2016 |
|
421cd2de-f058-465f-b890-dd8fcc0df273 |
This example shows how to use cancellation to implement a basic parallel search algorithm.
The following example uses cancellation to search for an element in an array. The parallel_find_any
function uses the concurrency::parallel_for algorithm and the concurrency::run_with_cancellation_token function to search for the position that contains the given value. When the parallel loop finds the value, it calls the concurrency::cancellation_token_source::cancel method to cancel future work.
[!code-cppconcrt-parallel-array-search#1]
The concurrency::parallel_for algorithm acts concurrently. Therefore, it does not perform the operations in a pre-determined order. If the array contains multiple instances of the value, the result can be any one of its positions.
Copy the example code and paste it in a Visual Studio project, or paste it in a file that is named parallel-array-search.cpp
and then run the following command in a Visual Studio Command Prompt window.
cl.exe /EHsc parallel-array-search.cpp
Cancellation in the PPL
Parallel Algorithms
parallel_for Function
cancellation_token_source Class