boost::cobalt Fast - Posted on Apr 07, 2024 - See https://www.boost.org/libs/cobalt - Logs Home - d0012
boost::cobalt Fast (c++)
co_return
#include <boost/cobalt.hpp> #include <iostream> namespace cobalt = boost::cobalt; cobalt::main co_main(int argc, char * argv[]) { std::cout << "Hello c++ cobalt!" << std::endl; co_return 0; }
g++ hello-world.cpp -std=c++23 -lboost_cobalt -o hello_world
lib boost-cobalt : : <name>boost_cobalt ; exe hello-world : hello-world.cpp : <library>boost-cobalt ;
co_await
co_return
The co_main function defines an implicit main when used and is the easiest way to set up an environment to run asynchronous code.
#include <boost/cobalt.hpp> #include <boost/cobalt/op.hpp> #include <boost/asio/steady_timer.hpp> #include <iostream> namespace cobalt = boost::cobalt; namespace asio = boost::asio; cobalt::main co_main(int argc, char * argv[]) { std::cout << "begin" << std::endl; asio::steady_timer timer{ co_await asio::this_coro::executor, std::chrono::seconds(2) }; co_await timer.async_wait(cobalt::use_op); std::cout << "end\n"; co_return 0; }
co_yield
#include <boost/cobalt.hpp> #include <boost/cobalt/op.hpp> #include <iostream> #include <thread> #include <chrono> namespace cobalt = boost::cobalt; class generator_box { public: cobalt::generator<int> operator()() const { int i = 0; while (true) co_yield i++; } }; cobalt::main co_main(int argc, char * argv[]) { auto g = generator_box{}(); while (true) { std::cout << "=> " << co_await g << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); } co_return 0; }
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
================================================== # The c++ programming language. # # # # Home: cppfx.xyz # # Join c++ Discord: yZcauUAUyC # # Deck # ==================================================