From 94b5c6a499f28a06f032e7781acab8f827dae418 Mon Sep 17 00:00:00 2001 From: Greg Zaitsev Date: Tue, 20 Aug 2019 23:58:24 +0300 Subject: [PATCH] Fixed message update race --- src/jsonrpc.cpp | 22 +++++++++++++++------- src/jsonrpc.h | 2 ++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/jsonrpc.cpp b/src/jsonrpc.cpp index 17d5c61..78d93cf 100644 --- a/src/jsonrpc.cpp +++ b/src/jsonrpc.cpp @@ -33,7 +33,10 @@ Json CJsonRpc::request(Json jsonMap, long timeout_s) { // build request Json request = Json::object{ - {"id", query.id}, {"jsonrpc", _jsonrpcVersion}, {"method", jsonMap["method"]}, {"params", jsonMap["params"]}, + {"id", query.id}, + {"jsonrpc", _jsonrpcVersion}, + {"method", jsonMap["method"]}, + {"params", jsonMap["params"]}, }; // Send the command @@ -59,6 +62,13 @@ Json CJsonRpc::request(Json jsonMap, long timeout_s) { return move(result); } +void CJsonRpc::delayedUpdateThread(Json message, int subscriptionId) { + usleep(1000000); + if (_wsSubscribers.count(subscriptionId) != 0) { + _wsSubscribers[subscriptionId]->handleWsMessage(subscriptionId, message["params"]["result"]); + } +} + void CJsonRpc::handleMessage(const string &payload) { string err; _logger->info(string("Message received: ") + payload); @@ -90,13 +100,11 @@ void CJsonRpc::handleMessage(const string &payload) { bool observerFound = (_wsSubscribers.count(subscriptionId) != 0); _queryMtx.unlock(); if (!observerFound) { - usleep(500000); - } - - _queryMtx.lock(); - if (_wsSubscribers.count(subscriptionId)) + std::thread t(&CJsonRpc::delayedUpdateThread, this, json, subscriptionId); + t.detach(); + } else { _wsSubscribers[subscriptionId]->handleWsMessage(subscriptionId, json["params"]["result"]); - _queryMtx.unlock(); + } } else { _logger->error("Unknown type of response: " + payload); } diff --git a/src/jsonrpc.h b/src/jsonrpc.h index d018b8f..fc0673d 100644 --- a/src/jsonrpc.h +++ b/src/jsonrpc.h @@ -31,6 +31,8 @@ class CJsonRpc : public IMessageObserver, public IJsonRpc { // Map between subscription IDs and subscribers map _wsSubscribers; + void delayedUpdateThread(Json message, int subscriptionId); + int getNextId(); public: