【发布时间】:2020-09-27 21:34:28
【问题描述】:
我正在尝试编写一个异步 tcp 客户端(客户端应该能够写入套接字而无需等待先前操作的结果到达)。
std::future<void> AsyncClient::SomeMethod(sometype& parameter)
{
return std::async(
std::launch::async,
[&]()
{
// Gonna send a json. ';' at the end of a json separates the requests.
const std::string requestJson = Serializer::ArraySumRequest(numbers) + ';';
boost::system::error_code err;
write(requestJson, err);
写法:
void AsyncClient::write(const std::string& strToWrite, boost::system::error_code& err)
{
// m_writeMutex is a class member I use to synchronize writing.
std::lock_guard<std::mutex> lock(m_writeMutex);
boost::asio::write(m_socket,
boost::asio::buffer(strToWrite), err);
}
但结果不是我所期望的。大多数情况下,我在服务器端收到的不是完整的请求,然后是 ;.
发生的事情是这样的:
一个请求:
{"Key":"Value"};{"Key":"Va下一个请求:
lue"};{"Key":"Value"};
为什么会这样?
【问题讨论】:
标签: c++ sockets asynchronous boost-asio race-condition