mutex on boost :: asio :: write nie działa

Sep 28 2020

Próbuję utworzyć asynchronicznego klienta TCP (nie będzie czekał na wynik żądania przed wysłaniem kolejnego żądania).

Metoda żądania wygląda następująco:

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 wywołuje metodę boost :: asio :: write w ten sposób:

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

Ale wygląda na to, że nadal wiele wątków zapisuje jednocześnie, ponieważ otrzymuję na serwerze:

{"Klucz": "Val {" Klucz ": Wartość}; ue"};

Co powinienem zrobić?

Odpowiedzi

3 Jeffrey Sep 28 2020 at 20:05

Postawiłeś strażnika zamka, pisząc do Asio . Jak widać, nie ma gwarancji, że drugi koniec będzie je przetwarzał z tym samym strażnikiem.

Powinieneś raczej umieścić strażnika tam, gdzie go potrzebujesz, podczas pisania json , z 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.