std::async
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
| Заголовочный файл <future>
|
||
| template< class Function, class... Args> std::future<typename std::result_of<Function(Args...)>::type> |
(1) | (начиная с C++11) |
| template< class Function, class... Args > std::future<typename std::result_of<Function(Args...)>::type> |
(2) | (начиная с C++11) |
async шаблон функции выполняет функцию f асинхронно (возможно, в отдельном потоке) и возвращает std::future, что будет в итоге результат этого вызова функции.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.
You can help to correct and verify the translation. Click here for instructions.
Ведет себя так же, как async(std::launch::async | std::launch::deferred, f, args...). Иными словами,
2) f может быть запущен в новый поток или он может быть запущен синхронно, когда в результате std::future запрашивается значение.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.
You can help to correct and verify the translation. Click here for instructions.
Вызывает функцию
f с аргументами args в соответствии с определенной политикой запуск 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.
You can help to correct and verify the translation. Click here for instructions.
- Если' асинхронных флаг установлен (т.е. policy & std::launch::async != 0), то
asyncпорождает новый поток исполнения, как по std::thread(f, args...), за исключением того, что если функцияfвозвращает значение или генерирует исключение, оно хранится в общем состоянии доступным через std::future, чтоasyncвозвращается к вызывающему.Original:If the async flag is set (i.e. policy & std::launch::async != 0), thenasyncspawns a new thread of execution as if by std::thread(f, args...), except that if the functionfreturns a value or throws an exception, it is stored in the shared state accessible through the std::future thatasyncreturns 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.
- Если отложенный' флаг установлен (т.е. policy & std::launch::deferred != 0), то
asyncновообращенныхargs...же, как и конструктором std::thread, но не породить новый поток выполнения. Вместо этого,' ленивая оценка производится: при первом вызове, не приурочен ждать функции на std::future, чтоasyncвозвращается вызывающему вызоветf(args...)должны быть выполнены в текущем потоке. Все последующие обращения к той же std::future будет возвращать результат сразу.Original:If the deferred flag is set (i.e. policy & std::launch::deferred != 0), thenasyncconvertsargs...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 thatasyncreturned to the caller will causef(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.
- Если оба std::launch::async и std::launch::deferred флаги установлены в
policy, это до реализации, выполнять ли асинхронное выполнение или ленивые вычисления.Original:If both the std::launch::async and std::launch::deferred flags are set inpolicy, 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.
Содержание |
[править] Параметры
| f | - | функции или функции объекта позвонить
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... | - | параметры для передачи
fOriginal: parameters to pass to fThe text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||||||||||||||||||||||
| policy | - | битовой маски значение, где отдельные биты управления разрешенные методы исполнения
Original: bitmask value, where individual bits control the allowed methods of execution
The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||||||||||||||||||||||
[править] Возвращаемое значение
std::future со ссылкой на возвращаемого значения функции.
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.
You can help to correct and verify the translation. Click here for instructions.
[править] Исключения
Выдает std::system_error с ошибкой std::errc::resource_unavailable_try_again условии, если запуск политика std::launch::async и осуществление не в состоянии начать новую тему.
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.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Реализация может расширять поведение первой перегрузки std::async путем предоставления дополнительных (осуществление определенных) биты в политику запуска по умолчанию.
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.
You can help to correct and verify the translation. Click here for instructions.
[править] Пример
#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'; }
Вывод:
The sum is 10000