Skip to content

Instantly share code, notes, and snippets.

@alz2
Created April 28, 2021 04:53
Example where fiber yield and fiber sleep_for makes a difference.
#include <boost/asio.hpp>
#include <boost/fiber/all.hpp>
#include <chrono>
#include <memory>
#include "testing/experimental/round_robin/round_robin.hpp" // For asio round robin scheduler.
// Context:
// https://stackoverflow.com/questions/67276482/difference-between-boostfiberyield-and-boostfibersleep-for-when-using-fib
int main(int argc, char **argv) {
auto io_context = std::make_shared<boost::asio::io_context>();
boost::fibers::use_scheduling_algorithm<boost::fibers::asio::round_robin>(
io_context);
boost::fibers::fiber fiber_1([&io_context] {
while (true) {
boost::asio::high_resolution_timer timer(*io_context,
std::chrono::seconds(1));
boost::fibers::promise<bool> pr;
boost::fibers::future<bool> fu = pr.get_future();
timer.async_wait([&pr](const auto &timer) { pr.set_value(true); });
fu.get(); // Suspends this fiber.
std::cout << "We made it!\n";
boost::this_fiber::yield();
}
});
fiber_1.detach();
boost::fibers::fiber fiber_2([] {
while (true) {
boost::this_fiber::yield();
// If we comment out yield() and replace with sleep, we get printouts.
// boost::this_fiber::sleep_for(std::chrono::milliseconds(10));
}
});
fiber_2.detach();
// Prevent io context from returning.
boost::asio::executor_work_guard<decltype(io_context->get_executor())> work{
io_context->get_executor()};
io_context->run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment