Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the boost socket read and write functions thread safe?

I use the boost.asio to implement the network communication. In Main thread, I create the TCP socket and connect the remote machine. Then start a working thread to read data from the socket. In the Main thread, the same socket is used to send data. That means the same socket is used in two threads without mutex. The code is pasted below. Is there any issue regarding the read and write functions of the socket?

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;
}
like image 404
Jeffrey Avatar asked Nov 14 '22 07:11

Jeffrey


1 Answers

No, this doesn't appear to be thread safe, per the bottom of http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/ip__tcp/socket.html, and previous answers at boost::asio::socket thread safety

like image 117
DavidN Avatar answered Dec 18 '22 13:12

DavidN