I use boost.asio to implement network communication. In the main thread, I create a TCP socket and connect the remote computer. Then run the workflow to read data from the socket. In the main stream, the same socket is used to send data. This means that the same socket is used in two threads without a mutex. The code will be inserted below. Is there a problem regarding read and write socket functions?
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);
}
}
int main()
{
Connect();
while(true)
{
boost::this_thread::sleep( boost::posix_time::seconds(1));
Send();
}
return 0;
}
source
share