#include <iostream>
#include <syncstream>
#include <thread>
struct tid_t {
friend std::ostream &operator<<(std::ostream &os, tid_t) {
return os << "(tid=" << std::this_thread::get_id() << ')';
}
};
inline constexpr tid_t tid;
template <typename Rep, typename Period>
void sleep_for(std::chrono::duration<Rep, Period> d) {
std::osyncstream(std::cout) << tid << ": about to sleep\n";
std::this_thread::sleep_for(d);
std::osyncstream(std::cout) << tid << ": about to return\n";
}
struct lifetime {
const char *txt = "active (default-constructed)";
lifetime() = default;
lifetime(const lifetime &) { txt = "active (copy-constructed)"; }
lifetime &operator=(const lifetime &) {
txt = "active (copy-assigned)";
return *this;
}
lifetime(lifetime &&other) noexcept {
txt = "active (move-constructed)", other.txt = "unspecified (move-constructed-from)";
}
lifetime &operator=(lifetime &&other) noexcept {
txt = "active (move-assigned)";
other.txt = "unspecified (move-assigned-from)";
return *this;
}
~lifetime() { txt = "destructed"; }
void operator()() const { std::cout << "[lifetime] " << txt << '\n'; }
};
int main() {
using namespace std::chrono_literals;
try {
{
auto func = [obj = lifetime {}] { obj(); };
}
{
auto func = [obj = lifetime {}] { obj(); };
}
{
auto a1 =
async([obj = lifetime {}] { obj(); });
auto a2 =
async([obj = lifetime {}] { obj(); });
auto a3 =
async([obj = lifetime {}] { obj(); });
}
{
async([] {
return 3; }),
async([] {
return 4; }));
std::cout << "v1: " << v1 << ", v2: " << v2 << ", v3: " << v3 << ", v4: " << v4 << '\n';
}
{
auto [v1, v2, v3, v4] =
async([] {
return 7; }),
async([] {
return 8; })));
std::cout << "v1: " << v1 << ", v2: " << v2 << ", v3: " << v3 << ", v4: " << v4 << '\n';
}
{
std::vector<task<void>> v;
for (int i = 0; i < 3; ++i)
v.push_back(make_task(
async([] { sleep_for(1s); })));
}
{
std::vector<task<void>> v;
for (int i = 0; i < 3; ++i)
v.push_back(make_task(
async([] { sleep_for(1s); })));
}
} catch (const std::exception &ex) {
std::cout << "Unhandled exception: " << ex.what() << '\n';
}
}
decltype(auto) sync_await(A &&awaitable)
Creates a synchronized task from the awaitable, starts it, and waits for it to complete,...
awaitable auto when_all(Awaitables &&...awaitables)