2010-07-16 44 views

回答

4

Boost Asio會很容易地做到這一點。查看the examples in the Highscore tutorial,其中顯示瞭如何使用Boost進行多線程異步輸入/輸出。

#include <boost/asio.hpp> 
#include <boost/thread.hpp> 
#include <iostream> 

void handler1(const boost::system::error_code &ec) 
{ 
    std::cout << "5 s." << std::endl; 
} 

void handler2(const boost::system::error_code &ec) 
{ 
    std::cout << "5 s." << std::endl; 
} 

boost::asio::io_service io_service; 

void run() 
{ 
    io_service.run(); 
} 

int main() 
{ 
    boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(5)); 
    timer1.async_wait(handler1); 
    boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(5)); 
    timer2.async_wait(handler2); 
    boost::thread thread1(run); 
    boost::thread thread2(run); 
    thread1.join(); 
    thread2.join(); 
} 
2

異步I/O比線程每客戶端模式在很多方面都要好一些。最佳性能實際上是通過每個內核線程實現的,每個線程執行異步I/O。

請注意,您的「多線程服務器」的概念雖然不完全錯誤,但與其他人使用該短語的含義截然不同。一般來說,它意味着每個連接一個線程,而不是跨線程並行化的一個連接的響應。

您要求的示例只是單線程同步服務器+並行計算的組合。