2012-04-05 85 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

回答