Espacios de nombres
Variantes
Acciones

std::async

De cppreference.com
< cpp‎ | thread


 
 
Tema Biblioteca de ayuda
Threads
Original:
Threads
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
thread(C++11)
this_thread espacio de nombres
Original:
this_thread namespace
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
get_id(C++11)
yield(C++11)
sleep_for(C++11)
sleep_until(C++11)
Exclusión mutua
Original:
Mutual exclusion
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
mutex(C++11)
timed_mutex(C++11)
Gestión de bloqueos genérico
Original:
Generic lock management
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
lock_guard(C++11)
unique_lock(C++11)
defer_lock_t
try_to_lock_t
adopt_lock_t
(C++11)
(C++11)
(C++11)
lock(C++11)
try_lock(C++11)
defer_lock
try_to_lock
adopt_lock
(C++11)
(C++11)
(C++11)
Las variables de condición
Original:
Condition variables
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
condition_variable(C++11)
condition_variable_any(C++11)
notify_all_at_thread_exit(C++11)
cv_status(C++11)
Futuros
Original:
Futures
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
promise(C++11)
future(C++11)
shared_future(C++11)
packaged_task(C++11)
async(C++11)
launch(C++11)
future_status(C++11)
future_error(C++11)
future_category(C++11)
future_errc(C++11)
 
Defined in header <future>
template< class Function, class... Args>

std::future<typename std::result_of<Function(Args...)>::type>

    async( Function&& f, Args&&... args );
(1) (desde C++11)
template< class Function, class... Args >

std::future<typename std::result_of<Function(Args...)>::type>

    async( std::launch policy, Function&& f, Args&&... args );
(2) (desde C++11)
El async función de plantilla se ejecuta la función f asíncrona (potencialmente en un hilo separado) y devuelve un std::future que eventualmente llevará a cabo el resultado de esa llamada a la función .
Original:
The template function async runs the function f asynchronously (potentially in a separate thread) and returns a std::future that will eventually hold the result of that function call.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
Se comporta igual que async(std::launch::async | std::launch::deferred, f, args...). En otras palabras, f se puede iniciar en un nuevo hilo o se puede ejecutar sincrónicamente cuando el std::future resultante se consulta para un valor .
Original:
Behaves the same as async(std::launch::async | std::launch::deferred, f, args...). In other words, f may be started in a new thread or it may be run synchronously when the resulting std::future is queried for a value.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Llama a una función con argumentos f args de acuerdo con una política de lanzamiento específica policy:
Original:
Calls a function f with arguments args according to a specific launch policy policy:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Si la bandera' async se establece (es decir, policy & std::launch::async != 0), entonces async genera un nuevo hilo de ejecución como por std::thread(f, args...), excepto que si la función f devuelve un valor o produce una excepción, que se almacena en el estado de acceso compartido a través de la std::future que async devuelve a la persona que llama .
    Original:
    If the async flag is set (i.e. policy & std::launch::async != 0), then async spawns a new thread of execution as if by std::thread(f, args...), except that if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si la bandera' diferido se activa (es decir, policy & std::launch::deferred != 0), entonces async convertidos args... la misma manera que por constructor std::thread, pero no generar un nuevo hilo de ejecución. En cambio, la evaluación perezosa' que se realiza la primera llamada a un no-programado esperar función en el std::future que async devuelve al llamador causará f(args...) que se ejecutará en el subproceso actual. Todos los accesos adicionales a la misma std::future devolverá el resultado inmediato .
    Original:
    If the deferred flag is set (i.e. policy & std::launch::deferred != 0), then async converts args... the same way as by std::thread constructor, but does not spawn a new thread of execution. Instead, lazy evaluation is performed: the first call to a non-timed wait function on the std::future that async returned to the caller will cause f(args...) to be executed in the current thread. All further accesses to the same std::future will return the result immediately.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si las banderas tanto de la std::launch::async y std::launch::deferred se establecen en policy, corresponde a la aplicación si desea realizar la ejecución asíncrona o evaluación perezosa .
    Original:
    If both the std::launch::async and std::launch::deferred flags are set in policy, it is up to the implementation whether to perform asynchronous execution or lazy evaluation.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Contenido

[editar] Parámetros

f -
objeto de función o la función a llamar
Original:
function or function object to call
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
args... -
parámetros que se pasan a f
Original:
parameters to pass to f
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
policy -
valor de máscara de bits, donde cada bit controlar los métodos permitidos de ejecución
Bit
Explicación
Original:
Explanation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
std::launch::async
permitir la evaluación asincrónica
Original:
enable asynchronous evaluation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
std::launch::deferred
permitir la evaluación perezosa
Original:
enable lazy evaluation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Original:
bitmask value, where individual bits control the allowed methods of execution
Bit
Explicación
Original:
Explanation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
std::launch::async
permitir la evaluación asincrónica
Original:
enable asynchronous evaluation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
std::launch::deferred
permitir la evaluación perezosa
Original:
enable lazy evaluation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Valor de retorno

std::future referencia al valor devuelto por la función .
Original:
std::future referring to the return value of the function.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Excepciones

Lanza std::system_error con std::errc::resource_unavailable_try_again condición de error si la política es std::launch::async lanzamiento y la puesta en práctica no puede iniciar un nuevo hilo .
Original:
Throws std::system_error with error condition std::errc::resource_unavailable_try_again if the launch policy is std::launch::async and the implementation is unable to start a new thread.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Notas

La implementación puede extender el comportamiento de la primera sobrecarga de std::async al permitir adicionales (definidos por la implementación) bits en la política de inicio predeterminada .
Original:
The implementation may extend the behavior of the first overload of std::async by enabling additional (implementation-defined) bits in the default launch policy.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Ejemplo

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future>
 
template <typename RAIter>
int parallel_sum(RAIter beg, RAIter end)
{
    typename RAIter::difference_type len = end-beg;
    if(len < 1000)
        return std::accumulate(beg, end, 0);
 
    RAIter mid = beg + len/2;
    auto handle = std::async(std::launch::async,
                              parallel_sum<RAIter>, mid, end);
    int sum = parallel_sum(beg, mid);
    return sum + handle.get();
}
 
int main()
{
    std::vector<int> v(10000, 1);
    std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';
}

Output:

The sum is 10000