Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Older Windows 11 PCs need a Secure Boot fix ASAP

    Why Ring’s Super Bowl ad hits so sinister

    This dual-CPU PC from 1995 was so cool, Microsoft had to kill it

    Facebook X (Twitter) Instagram
    • Artificial Intelligence
    • Business Technology
    • Cryptocurrency
    • Gadgets
    • Gaming
    • Health
    • Software and Apps
    • Technology
    Facebook X (Twitter) Instagram Pinterest Vimeo
    Tech AI Verse
    • Home
    • Artificial Intelligence

      Read the extended transcript: President Donald Trump interviewed by ‘NBC Nightly News’ anchor Tom Llamas

      February 6, 2026

      Stocks and bitcoin sink as investors dump software company shares

      February 4, 2026

      AI, crypto and Trump super PACs stash millions to spend on the midterms

      February 2, 2026

      To avoid accusations of AI cheating, college students are turning to AI

      January 29, 2026

      ChatGPT can embrace authoritarian ideas after just one prompt, researchers say

      January 24, 2026
    • Business

      New VoidLink malware framework targets Linux cloud servers

      January 14, 2026

      Nvidia Rubin’s rack-scale encryption signals a turning point for enterprise AI security

      January 13, 2026

      How KPMG is redefining the future of SAP consulting on a global scale

      January 10, 2026

      Top 10 cloud computing stories of 2025

      December 22, 2025

      Saudia Arabia’s STC commits to five-year network upgrade programme with Ericsson

      December 18, 2025
    • Crypto

      HBAR Shorts Face $5 Million Risk if Price Breaks Key Level

      February 10, 2026

      Ethereum Holds $2,000 Support — Accumulation Keeps Recovery Hopes Alive

      February 10, 2026

      Miami Mansion Listed for 700 BTC as California Billionaire Tax Sparks Relocations

      February 10, 2026

      Solana Drops to 2-Year Lows — History Suggests a Bounce Toward $100 is Incoming

      February 10, 2026

      Bitget Cuts Stock Perps Fees to Zero for Makers Ahead of Earnings Season, Expanding Access Across Markets

      February 10, 2026
    • Technology

      Older Windows 11 PCs need a Secure Boot fix ASAP

      February 11, 2026

      Why Ring’s Super Bowl ad hits so sinister

      February 11, 2026

      This dual-CPU PC from 1995 was so cool, Microsoft had to kill it

      February 11, 2026

      1,300 games for $10: ‘No ICE in Minnesota’ bundle launched

      February 11, 2026

      Gemini gave my Plex server a checkup. Its diagnosis surprised me

      February 11, 2026
    • Others
      • Gadgets
      • Gaming
      • Health
      • Software and Apps
    Check BMI
    Tech AI Verse
    You are at:Home»Technology»C++ Coroutines Advanced: Converting std:future to asio:awaitable
    Technology

    C++ Coroutines Advanced: Converting std:future to asio:awaitable

    TechAiVerseBy TechAiVerseJuly 15, 2025No Comments2 Mins Read5 Views
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Share
    Facebook Twitter LinkedIn Pinterest WhatsApp Email

    C++ Coroutines Advanced: Converting std:future to asio:awaitable

    July 15, 2025 · 696 words · 4 min

    • Problem Background
    • Core Solution
      • Core Implementation
    • Usage Examples
      • Basic Usage
      • Exception Handling
    • Technical Points Analysis
      • 1. Advantages of Using async_initiate
      • 2. Thread Pool Design
      • 3. Exception Handling Strategy
      • 4. Executor Context Preservation
    • Performance Considerations
    • Practical Application Scenarios
    • Summary

    In modern C++ development, coroutines have brought revolutionary changes to asynchronous programming. However, when using boost::asio or standalone asio, we often encounter scenarios where we need to convert traditional std::future to asio::awaitable. This article will detail an efficient, thread-safe conversion method.

    Problem Background

    When using asio coroutines, we often encounter scenarios like:

    • Need to call third-party libraries that return std::future (such as database drivers)
    • Want to use co_await in coroutines to handle these asynchronous operations
    • Don’t want to block IO threads, maintaining high performance

    Traditional solutions might use timer polling or directly call future.get() in IO threads, but these methods are either inefficient or block IO threads.

    Core Solution

    Our solution is based on asio::async_initiate, which provides perfect integration with the asio coroutine system while avoiding the problem of blocking IO threads.

    Core Implementation

    #include 
    #include 
    #include 
    #include 
    
    // Thread pool for handling blocking operations
    asio::thread_pool blocking_pool(4);
    
    // Convert std::future to asio::awaitable
    template<typename T, typename CompletionToken>
    auto future_to_awaitable(std::future<T> future, CompletionToken&& token) {
        return asio::async_initiate<CompletionToken, void(std::tuple<std::optional<T>, std::exception_ptr>)>(
            [future = std::move(future)](auto&& handler) mutable {
                auto executor = asio::get_associated_executor(handler);
                
                // Execute blocking operation in thread pool to avoid blocking IO thread
                asio::post(blocking_pool, [future = std::move(future), handler = std::move(handler), executor]() mutable {
                    std::tuple<std::optional<T>, std::exception_ptr> result;
                    
                    try {
                        T value = future.get();
                        result = std::make_tuple(std::make_optional(std::move(value)), nullptr);
                    } catch (...) {
                        result = std::make_tuple(std::nullopt, std::current_exception());
                    }
                    
                    // Return to original executor context to call handler
                    asio::post(executor, [handler = std::move(handler), result = std::move(result)]() mutable {
                        handler(std::move(result));
                    });
                });
            },
            token
        );
    }
    
    // Wrapper function specifically for coroutines
    template<typename T>
    asio::awaitable<T> await_future(std::future<T> future) {
        auto [result, exception] = co_await future_to_awaitable(std::move(future), asio::use_awaitable);
        
        if (exception) {
            std::rethrow_exception(exception);
        }
        
        if (result) {
            co_return std::move(*result);
        }
        
        throw std::runtime_error("Unknown error: no result and no exception");
    }
    

    Usage Examples

    Basic Usage

    // Simulate database query
    std::future<std::string> query_mysql(const std::string& sql) {
        return std::async(std::launch::async, [sql] {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            return "Query result for: " + sql + " - Found 10 rows";
        });
    }
    
    // Use in coroutine
    asio::awaitable<void> example_coro() {
        try {
            // Directly await future in coroutine
            auto result = co_await await_future(query_mysql("SELECT * FROM users"));
            std::cout << "Query successful: " << result << std::endl;
        } catch (const std::exception& e) {
            std::cout << "Query failed: " << e.what() << std::endl;
        }
    }
    

    Exception Handling

    std::future<std::string> query_with_error(const std::string& sql) {
        return std::async(std::launch::async, [sql]() -> std::string {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            throw std::runtime_error("Database connection failed");
        });
    }
    
    asio::awaitable<void> error_handling_example() {
        try {
            auto result = co_await await_future(query_with_error("SELECT * FROM invalid_table"));
            std::cout << "Should not reach here" << std::endl;
        } catch (const std::exception& e) {
            std::cout << "Exception caught: " << e.what() << std::endl;
        }
    }
    

    Technical Points Analysis

    1. Advantages of Using async_initiate

    • Perfect Integration: Seamlessly integrates with asio coroutine system
    • Type Safety: Compile-time type checking
    • Performance Optimization: Avoids timer polling overhead

    2. Thread Pool Design

    asio::thread_pool blocking_pool(4);
    
    • Dedicated to handling blocking operations
    • Avoids blocking IO threads
    • Thread count can be adjusted as needed

    3. Exception Handling Strategy

    Using std::tuple, std::exception_ptr> to handle two scenarios:

    • Normal result: {std::optional, nullptr}
    • Exception case: {std::nullopt, std::exception_ptr}

    This design correctly handles edge cases, such as when the return type itself is std::exception_ptr.

    4. Executor Context Preservation

    auto executor = asio::get_associated_executor(handler);
    // ...
    asio::post(executor, [handler = std::move(handler), result = std::move(result)]() mutable {
        handler(std::move(result));
    });
    

    Ensures that the final handler call occurs in the correct executor context, maintaining asio’s executor semantics.

    Performance Considerations

    1. Avoid IO Thread Blocking: All blocking operations are executed in independent thread pools
    2. Move Semantics: Extensive use of std::move to avoid unnecessary copying
    3. Zero-Copy Design: Results are passed directly between threads without additional copying

    Practical Application Scenarios

    This conversion method is particularly suitable for the following scenarios:

    1. Database Operations: Converting database driver async interfaces to coroutine-friendly forms
    2. File I/O: Handling potentially blocking file operations
    3. Third-Party Library Integration: Integrating with libraries that return std::future
    4. CPU-Intensive Tasks: Converting CPU-intensive tasks to awaitable forms

    Summary

    By using asio::async_initiate and thread pools, we’ve implemented an efficient, thread-safe solution for converting std::future to asio::awaitable. This approach not only avoids blocking IO threads but also provides perfect exception handling mechanisms, making it one of the best practices for modern C++ asynchronous programming.

    This design pattern can be easily extended to other asynchronous scenarios, laying a solid foundation for building high-performance coroutine applications.

    Lunet: Design and Implementation of a High-Performance Coroutine Network Library

    Share. Facebook Twitter Pinterest LinkedIn Reddit WhatsApp Telegram Email
    Previous ArticleIs Nano-Hydroxyapatite Toothpaste an Effective Fluoride Alternative? Dentists Weigh In
    Next Article Show HN: CallFS – S3-style object store in one Go binary (MIT)
    TechAiVerse
    • Website

    Jonathan is a tech enthusiast and the mind behind Tech AI Verse. With a passion for artificial intelligence, consumer tech, and emerging innovations, he deliver clear, insightful content to keep readers informed. From cutting-edge gadgets to AI advancements and cryptocurrency trends, Jonathan breaks down complex topics to make technology accessible to all.

    Related Posts

    Older Windows 11 PCs need a Secure Boot fix ASAP

    February 11, 2026

    Why Ring’s Super Bowl ad hits so sinister

    February 11, 2026

    This dual-CPU PC from 1995 was so cool, Microsoft had to kill it

    February 11, 2026
    Leave A Reply Cancel Reply

    Top Posts

    Ping, You’ve Got Whale: AI detection system alerts ships of whales in their path

    April 22, 2025664 Views

    Lumo vs. Duck AI: Which AI is Better for Your Privacy?

    July 31, 2025250 Views

    6.7 Cummins Lifter Failure: What Years Are Affected (And Possible Fixes)

    April 14, 2025151 Views

    6 Best MagSafe Phone Grips (2025), Tested and Reviewed

    April 6, 2025111 Views
    Don't Miss
    Technology February 11, 2026

    Older Windows 11 PCs need a Secure Boot fix ASAP

    Older Windows 11 PCs need a Secure Boot fix ASAP Image: Microsoft Summary created by…

    Why Ring’s Super Bowl ad hits so sinister

    This dual-CPU PC from 1995 was so cool, Microsoft had to kill it

    1,300 games for $10: ‘No ICE in Minnesota’ bundle launched

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    About Us
    About Us

    Welcome to Tech AI Verse, your go-to destination for everything technology! We bring you the latest news, trends, and insights from the ever-evolving world of tech. Our coverage spans across global technology industry updates, artificial intelligence advancements, machine learning ethics, and automation innovations. Stay connected with us as we explore the limitless possibilities of technology!

    Facebook X (Twitter) Pinterest YouTube WhatsApp
    Our Picks

    Older Windows 11 PCs need a Secure Boot fix ASAP

    February 11, 20262 Views

    Why Ring’s Super Bowl ad hits so sinister

    February 11, 20263 Views

    This dual-CPU PC from 1995 was so cool, Microsoft had to kill it

    February 11, 20263 Views
    Most Popular

    7 Best Kids Bikes (2025): Mountain, Balance, Pedal, Coaster

    March 13, 20250 Views

    VTOMAN FlashSpeed 1500: Plenty Of Power For All Your Gear

    March 13, 20250 Views

    This new Roomba finally solves the big problem I have with robot vacuums

    March 13, 20250 Views
    © 2026 TechAiVerse. Designed by Divya Tech.
    • Home
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.