【发布时间】:2021-01-14 10:12:40
【问题描述】:
我正在尝试创建一个异步 tcp 客户端(它不会在发送另一个请求之前等待请求的结果)。
请求方法如下:
std::future<void> AsyncClient::SomeRequestMethod(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);
// Other stuff.
write 方法调用 boost::asio::write 像这样:
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":"Val{"Key":Value};ue"};
我该怎么办?
【问题讨论】:
标签: c++ sockets asynchronous boost-asio race-condition