Last active
July 13, 2021 17:00
-
-
Save luluco250/078420e218f5492820ceb58717e661a8 to your computer and use it in GitHub Desktop.
Example of using concurrent asynchronous tasks in C++
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 <future> | |
#include <chrono> | |
#include <thread> | |
using namespace std::literals; | |
static std::mutex println_mutex; | |
constexpr auto println = [](auto... stuff) { | |
std::lock_guard guard(println_mutex); | |
(std::cout << ... << stuff) << std::endl; | |
}; | |
constexpr auto sleep_for = [](auto x) { | |
std::this_thread::sleep_for(x); | |
}; | |
void get_bread() { | |
println("[bread] Making dough..."); | |
sleep_for(2s); | |
println("[bread] Shaping dough..."); | |
sleep_for(2s); | |
println("[bread] Preheating oven..."); | |
sleep_for(2s); | |
println("[bread] Baking dough..."); | |
sleep_for(4s); | |
println("[bread] Taking bread out of the oven..."); | |
sleep_for(1s); | |
println("[bread] Bread baked!"); | |
} | |
void get_ham() { | |
println("[ham] Going to the market..."); | |
sleep_for(10s); | |
println("[ham] Looking for ham..."); | |
sleep_for(3s); | |
println("[ham] At the cashier..."); | |
sleep_for(5s); | |
println("[ham] Going back home..."); | |
sleep_for(10s); | |
println("[ham] We have ham!"); | |
} | |
int main() { | |
{ | |
auto bread = std::async(get_bread); | |
auto ham = std::async(get_ham); | |
} | |
println("We have a sandwich!"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment