Espaços nominais
Variantes
Acções

std::async

Da cppreference.com
< cpp‎ | thread


 
 
Biblioteca de suporte a discussão
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 namespace
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)
Exclusão mútua
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)
Gestão de bloqueio 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)
Variáveis ​​de condição
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) (a partir do 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) (a partir do C++ 11)
O async função de modelo executa a função f de forma assíncrona (potencialmente em um segmento separado) e retorna uma std::future que acabará por manter o resultado dessa chamada função.
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)
Comporta o mesmo que async(std::launch::async | std::launch::deferred, f, args...). Em outras palavras, f pode ser iniciado em um novo segmento ou pode ser executado de forma síncrona quando o std::future resultante é consultado para um 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)
Chama uma função com argumentos f args de acordo com uma política de lançamento específico 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.
  • Se a bandeira async está definido (ou seja, policy & std::launch::async != 0), então async gera uma nova thread de execução, como se por std::thread(f, args...), exceto que se a função f retorna um valor ou lança uma exceção, ele é armazenado no estado compartilhada acessível por meio do que std::future async retorna ao chamador.
    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.
  • Se a bandeira diferido é definida (ou seja, policy & std::launch::deferred != 0), então async convertidos args... da mesma forma que pelo construtor std::thread, mas não gerar um novo segmento de execução. Em vez disso,' avaliação preguiçosa é realizado: a primeira chamada para um não-cronometrado função esperar no std::future que async retornado para o chamador irá causar f(args...) a ser executado no segmento atual. Todos os acessos adicionais à std::future mesmo irá retornar o resultado imediatamente.
    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.
  • Se bandeiras tanto std::launch::async e std::launch::deferred são definidos em policy, é até a implementação se para realizar a execução assíncrona ou avaliação preguiçosa.
    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.

Índice

[editar] Parâmetros

f -
objeto de função ou função a ser chamada
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 para passar para 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 bitmask, onde os bits individuais controlar os métodos permitidos de execução
Bit
Explicação
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 a avaliação assíncrona
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 a avaliação preguiçosa
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
Explicação
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 a avaliação assíncrona
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 a avaliação preguiçosa
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 referindo-se ao valor de retorno da função.
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] Exceções

Lança std::system_error com std::errc::resource_unavailable_try_again condição de erro se a política de lançamento é std::launch::async ea implementação não é capaz de iniciar um novo tópico.
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

A implementação pode estender o comportamento da primeira sobrecarga de std::async permitindo adicionais (aplicação definida) bits na política de lançamento padrão.
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] Exemplo

#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