Created
September 30, 2019 03:19
-
-
Save vic4key/76c10c8754636a8cc6d96eff1adbb06b to your computer and use it in GitHub Desktop.
C++ STD Asynchronous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <future> | |
int main(int argc, char const *argv[]) | |
{ | |
auto fn_sync = [](int v) | |
{ | |
std::cout << v << std::endl; | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
}; | |
const auto start = std::chrono::high_resolution_clock::now(); | |
{ | |
// Sync - 1s | |
fn_sync(-1); | |
// Async For - 3s | |
const int nasync = 3; | |
std::vector<std::future<void>> futures; | |
for (int i = 0; i < nasync; ++i) | |
{ | |
auto fn_async = std::async(std::launch::async, fn_sync, i); // std::launch::deferred | |
futures.push_back(std::move(fn_async)); | |
} | |
for (auto& future : futures) | |
{ | |
future.wait(); | |
} | |
// Async Each - 3s | |
auto v1 = std::async(std::launch::async, fn_sync, 0); | |
auto v2 = std::async(std::launch::async, fn_sync, 1); | |
auto v3 = std::async(std::launch::async, fn_sync, 2); | |
v1.wait(); | |
v2.wait(); | |
v3.wait(); | |
} | |
const auto finish = std::chrono::high_resolution_clock::now(); | |
std::chrono::duration<double> elapsed = finish - start; | |
std::cout << "Total " << elapsed.count() << " seconds" << std::endl; | |
return 0; | |
} | |
/** | |
* -1 | |
* 0 | |
* 1 | |
* 2 | |
* 0 | |
* 1 | |
* 2 | |
* Total 3.00961 seconds | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment