#include <filesystem>
#include <fstream>
#include <iostream>
#include <source_location>
#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;
std::jthread worker;
struct awaitable {
awaitable(std::filesystem::path path) : path_(std::move(path)) {}
static bool await_ready() noexcept { return false; }
void await_suspend(std::coroutine_handle<> handle) {
auto work = [handle, this] {
std::osyncstream(std::cout)
<< tid << " worker thread: opening file " << path_ << '\n';
auto stream = std::ifstream(path_);
std::osyncstream(std::cout) << tid << " worker thread: reading file\n";
result_.assign(std::istreambuf_iterator<char>(stream),
std::istreambuf_iterator<char>());
std::osyncstream(std::cout) << tid << " worker thread: resuming coro\n";
handle.resume();
std::osyncstream(std::cout) << tid << " worker thread: exiting\n";
};
worker = std::jthread(work);
}
std::string await_resume() noexcept { return std::move(result_); }
private:
const std::filesystem::path &path_;
std::string result_;
};
std::osyncstream(std::cout) << tid << " readFile(): about to read file async\n";
const std::string result = co_await awaitable(path);
std::osyncstream(std::cout) << tid << " readFile(): about to return (size " << result.size()
<< ")\n";
co_return result.size();
}
void f1(const std::filesystem::path &path) {
auto t = async_read_file(path);
std::osyncstream(std::cout) <<
"Result: " <<
sync_await(t) <<
'\n';
}
auto t = async_read_file(path);
std::osyncstream(std::cout) << "Result: " << co_await t << '\n';
}
int main() {
try {
auto path = "/etc/passwd";
f1(path);
} catch (const std::exception &ex) {
std::osyncstream(std::cout) << "Unhandled exception: " << ex.what() << '\n';
}
}
Task that produces a value of type T: to get that value, simply await the task.
decltype(auto) sync_await(A &&awaitable)
Creates a synchronized task from the awaitable, starts it, and waits for it to complete,...