【问题标题】:Are the boost socket read and write functions thread safe?boost socket 读写函数是线程安全的吗?
【发布时间】:2013-12-31 11:28:57
【问题描述】:

我使用 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;
}

【问题讨论】:

  • 发送和接收使用不同的缓冲区,所以在低级别可能没问题。但是,错误是在低级别共享的,因此这当然会传播到您在不同线程中使用 Boost。

标签: c++ boost thread-safety boost-asio


【解决方案1】:

【讨论】:

    猜你喜欢
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2023-03-29
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多