5

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;
}
Sam Miller
  • 23,808
  • 4
  • 67
  • 87
Jeffrey
  • 4,436
  • 9
  • 38
  • 54
  • 2
    Sending and receiving uses different buffers, so on the low level it might be okay. However, errors are shared on the low level, so that will of course propagate up to your use of Boost in different threads. – Some programmer dude Apr 05 '12 at 06:40

1 Answers1

1

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

Community
  • 1
  • 1
David Neiss
  • 8,161
  • 2
  • 20
  • 21