Created
August 24, 2023 19:11
-
-
Save jwinarske/25c359a82742ee778e6ee2a356dc51bd to your computer and use it in GitHub Desktop.
asio strand example
This file contains hidden or 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 <chrono> | |
| #include <thread> | |
| #include <future> | |
| #include "asio/post.hpp" | |
| #include "asio/io_service.hpp" | |
| #include "asio/io_service_strand.hpp" | |
| void asyncRun() { | |
| std::cout << "Async..." << std::flush; | |
| asio::io_service io_service; | |
| auto work = asio::make_work_guard(io_service); | |
| asio::io_service::strand strand = asio::io_service::strand(io_service); | |
| std::thread t1([&io_service] { io_service.run(); }); | |
| t1.detach(); | |
| std::shared_ptr<std::promise<int> > promise(new std::promise<int>()); | |
| std::future<int> future = promise->get_future(); | |
| asio::post(strand, | |
| [promise]() { | |
| std::chrono::milliseconds dura(1000); | |
| std::this_thread::sleep_for(dura); | |
| promise->set_value(9); | |
| } | |
| ); | |
| std::cout << "Waiting..." << std::flush; | |
| future.wait(); | |
| work.reset(); | |
| std::cout << "Done!\nResults are: " | |
| << future.get() << '\n'; | |
| } | |
| void nonBlockingRun() { | |
| std::cout << "Non Blocking..." << std::flush; | |
| std::promise<int> promise; | |
| std::future<int> future = promise.get_future(); | |
| std::thread t1([](std::promise<int> p) { | |
| std::chrono::milliseconds dura(1000); | |
| std::this_thread::sleep_for(dura); | |
| p.set_value(9); | |
| }, | |
| std::move(promise)); | |
| t1.detach(); | |
| std::cout << "Waiting...\n" << std::flush; | |
| std::future_status status; | |
| do { | |
| status = future.wait_for(std::chrono::seconds(0)); | |
| if (status == std::future_status::deferred) { | |
| std::cout << "+"; | |
| } else if (status == std::future_status::timeout) { | |
| std::cout << "."; | |
| } | |
| } while (status != std::future_status::ready); | |
| std::cout << "Done!\nResults are: " | |
| << future.get() << '\n'; | |
| } | |
| void blockingRun() { | |
| std::cout << "Blocking..." << std::flush; | |
| std::promise<int> promise; | |
| std::future<int> future = promise.get_future(); | |
| std::thread t1([](std::promise<int> p) { | |
| std::chrono::milliseconds dura(1000); | |
| std::this_thread::sleep_for(dura); | |
| p.set_value(9); | |
| }, | |
| std::move(promise)); | |
| t1.detach(); | |
| std::cout << "Waiting..." << std::flush; | |
| future.wait(); | |
| std::cout << "Done!\nResults are: " | |
| << future.get() << '\n'; | |
| } | |
| int main() { | |
| nonBlockingRun(); | |
| blockingRun(); | |
| asyncRun(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment