5

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

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;
}
4

1 回答 1

1

不,这似乎不是线程安全的,根据http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/ip__tcp/socket.html的底部,以及以前的答案boost::asio::socket 线程安全

于 2013-12-31T03:28:57.453 回答