簡體   English   中英

通過boost :: asio poll避免繁忙的等待

[英]avoiding busy wait with boost::asio poll

我正在一個while循環中在io_service :: poll上使用boost :: asio :: io_service的linux上編寫服務。 這是一個繁忙的等待循環,例如,它浪費了CPU周期。

void Application::run()
{
    try
    {
        std::cout << "TcpServer starting..\n";
        _TcpServer.reset( new TcpServer(_io_service, boost::ref(_spState)) );

        // _io_service.run();

        while( ! _spState->QuitSignalled() )
        {
            _io_service.poll(); 
        }

        std::cerr << "quit signalled, TcpServer stopping.. :/" << std::endl;
    }
    catch(std::exception & e)
    {
        std::cout << e.what() << "\n";
    }
}

我使用poll而不是run來檢查服務中的另一個線程是否已發出信號表明服務已關閉。

有沒有一種方法可以在繁忙的等待循環中不使用輪詢來實現?

該服務在單個線程上使用async io,其他線程進行數據處理。

我在循環的迭代之間添加了一個睡眠,這似乎減少了cpu時間的浪費,但是我希望有一種更有效的方法嗎?

void Application::run()
{
    using boost::this_thread::sleep_for;

    static const boost::chrono::milliseconds napMsecs( 50 );

    try
    {
        std::cout << "TcpServer starting..\n";
        _TcpServer.reset( new TcpServer(_io_service, boost::ref(_spState)) );

        // _io_service.run();

        while( ! _spState->QuitSignalled() )
        {
            _io_service.poll();
            boost::this_thread::sleep_for( napMsecs );
        }

        std::cerr << "quit signalled, TcpServer stopping.. :/" << std::endl;
    }
    catch(std::exception & e)
    {
        std::cout << e.what() << "\n";
    }
}

我會說,只是利用boost::asio::io_service默認情況下是完全線程安全的事實,然后執行

iosvc.run();

並在“服務中的另一個線程”上發出信號,指示服務關閉:

iosvc.stop();

根據iosvc.reset()請記住在iosvc.reset()調用{run,poll}[_one]之前先使用iosvc.reset()

當然,您還可以使用其他方式來通知實際的邏輯工作者結束,但是那是完全獨立的,與Boost Asio無關

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM