mutex su boost :: asio :: write non funziona

Sep 28 2020

Sto cercando di creare un client tcp asincrono (non aspetterà il risultato di una richiesta prima di inviare un'altra richiesta).

Un metodo di richiesta è simile a:

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.

scrivi chiamate al metodo boost :: asio :: scrivi in ​​questo modo:

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);
}

Ma sembra che più thread scrivano contemporaneamente poiché ciò che ricevo nel server è come:

{"Key": "Val {" Key ": Value}; ue"};

Cosa dovrei fare?

Risposte

3 Jeffrey Sep 28 2020 at 20:05

Hai messo la guardia della serratura a scrivere all'ASIO . Come puoi vedere, non c'è alcuna garanzia che l'altra estremità li farà processare con la stessa guardia.

Dovresti piuttosto mettere la guardia dove ne hai bisogno, scrivendo il json , fuori dall'asio:

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.