2012-04-05 89 views
5

我使用boost.asio来实现网络通信。在主线程中,我创建TCP套接字并连接远程机器。然后启动一个工作线程从套接字读取数据。在主线程中,使用相同的套接字来发送数据。这意味着相同的套接字在没有互斥体的两个线程中使用。代码粘贴在下面。有没有关于套接字的读写功能的问题?boost套接字读写函数是否安全?

boost::asio::io_service   m_io_service; 
boost::asio::ip::tcp::socket m_socket(m_io_service); 
boost::thread*     m_pReceiveThread; 

void Receive(); 

void Connect() 
{ 
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 13); 
    m_socket.connect(endpoint); 

    m_pReceiveThread = new boost::thread(Receive); 
} 

void Send() 
{ 
    std::wstring strData(L"Message"); 
    boost::system::error_code error; 
    const std::size_t byteSize = boost::asio::write(m_socket, boost::asio::buffer(strData), error); 
} 


void Receive() 
{ 
    for (;;) 
    { 
     boost::array<wchar_t, 128> buf = {0}; 
     boost::system::error_code error; 

     const std::size_t byteSize = m_socket.read_some(boost::asio::buffer(buf), error); 

     // Dispatch the received data through event notification. 
    } 
} 

int main() 
{ 

    Connect(); 

    while(true) 
    { 
     boost::this_thread::sleep(boost::posix_time::seconds(1)); 
     Send(); 

    } 

    return 0; 
} 
+2

发送和接收使用不同的缓冲区,因此在较低水平,可能会好起来。但是,错误在低级别上共享,所以当然会传播到您在不同线程中使用Boost。 – 2012-04-05 06:40:13

回答