boost :: asio :: write üzerinde mutex çalışmıyor
Sep 28 2020
Zaman uyumsuz bir tcp istemcisi yapmaya çalışıyorum (başka bir istek göndermeden önce bir isteğin sonucunu beklemeyecek).
Bir istek yöntemi şuna benzer:
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.
metot çağrıları yazma boost :: asio :: şu şekilde yaz:
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);
}
Ancak, sunucuda aldığım gibi hala birden çok iş parçacığı aynı anda yazıyor gibi görünüyor:
{"Anahtar": "Değer {" Anahtar ": Değer}; ue"};
Ne yapmalıyım?
Yanıtlar
3 Jeffrey Sep 28 2020 at 20:05
Asio'ya yazmak için kilit korumasını koydunuz . Gördüğünüz gibi, diğer ucun onları aynı korumayla işlemesini sağlayacak hiçbir garanti yok.
Korumayı asio dışında json yazarken ihtiyacınız olan yere koymayı tercih etmelisiniz :
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);
}
return std::async(
std::launch::async,
[&]()
{
std::lock_guard<std::mutex> lock(m_writeMutex); // <--- here
// 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.
Gene Simmons, KISS Çizgi Romanlarının Potansiyel Olarak "İnsanlığı Yeniden Yaratabileceğini" Söyledi
Nicole Kidman, Michael Keaton ve Val Kilmer'in Batman Olarak Paylaştığı Bu 1 Çekici Özelliğe Bayıldı
Kevin Jonas'ın Kızı Alena, Doğum Günü Fotoğrafında Büyümüş Görünüyor: '9 Yaşında Gerçek Hissetmiyor'