簡體   English   中英

boost :: asio io_service線程池

[英]boost::asio io_service thread pool

為io_service設置線程池的正確用法是什么? 文檔中的這兩個陳述讓我失望:

io_service對象::運行

run()函數的正常退出意味着io_service對象已停止(stopped()函數返回true)。 除非事先調用reset(),否則對run(),run_one(),poll()或poll_one()的后續調用將立即返回。

io_service對象::復位

當由於io_service被停止或用完而導致先前調用這些函數時,必須在run(),run_one(),poll()或poll_one()函數的任何第二次或更高版本的調用之前調用此函數。工作。

這是我目前正在做的事情:

boost::thread_group     m_Threads;
boost::asio::io_service m_IoService;
boost::barrier          m_Barrier(numThreads);

for( unsigned int i = 0; i < numThreads; ++i )
{
    m_Threads.create_thread(
        [&]()
        {
            for(;;)
            {
                m_IoService.run();

                if( m_Barrier.wait() )  //  will only return true for 1 thread
                {
                    m_IoService.reset();
                }
                m_Barrier.wait();
            }
        });
}

m_IoService.stop();
m_Threads.interrupt_all();
m_Threads.join_all();

一切似乎都正常工作,如果我只是把m_IoService.run()無限循環(該文件似乎表明應該是這樣的)。 什么是正確的方法?

run()是一個阻塞調用,並將在返回之前執行它可以執行的所有事件。 只有在沒有更多事件需要處理時它才會返回。 一旦它返回,你必須在再次調用run()之前調用io_service上的reset()

你可以有多個線程調用run() - 這不是問題,只要io_service有一些工作要做,你就不需要無限循環。 正常的模式是在io_service上創建一個work對象,它將強制run()永不返回。 這意味着你必須在完成后明確地調用io_service上的stop() ,因為它永遠不會自然退出。

如果您在io_service上設置work ,它將永遠不會自然退出,因此您永遠不需要調用reset()

work some_work(m_IoService); // this will keep the io_service live.

for( unsigned int i = 0; i < numThreads; ++i )
{
  m_Threads.create_thread(
    [&]()
    {
      m_IoService.run();
    });
}

現在所有線程都在io_service上調度事件

// Now post your jobs
m_IoService.post(boost::bind(...)); // this will be executed in one of the threads
m_IoService.post(boost::bind(...)); // this will be executed in one of the threads
m_IoService.post(boost::bind(...)); // this will be executed in one of the threads

m_IoService.stop(); // explicitly stop the io_service
// now join all the threads and wait for them to exit

暫無
暫無

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

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