diff --git a/src/lib/io/websocket/websocket_client.cpp b/src/lib/io/websocket/websocket_client.cpp index f922875b1..1ec6223a5 100644 --- a/src/lib/io/websocket/websocket_client.cpp +++ b/src/lib/io/websocket/websocket_client.cpp @@ -9,6 +9,7 @@ #include "lib/io/websocket/websocket_error_code.h" #include "lib/io/websocket/websocketpp_exception_formatter.h" #include "lib/logging/logging.h" +#include "lib/utils/LockBox.h" #include "lib/utils/bts_assert.h" #include "lib/utils/formatters/exception_formatter.h" #include "lib/utils/thread_manager.h" @@ -110,6 +111,7 @@ using std::size_t; using std::string; using std::thread; using std::uint32_t; +using std::vector; using std::chrono::nanoseconds; using std::this_thread::sleep_for; @@ -151,8 +153,8 @@ struct WebsocketClient::PImpl { optional close_handler; size_t sub_id_counter{0}; string server_name; - optional io_thread; optional ping_thread; + utils::LockBox> io_threads; int client_id{client_id_counter++}; mutex instance_mx; State state = State::IDLE; @@ -199,9 +201,17 @@ struct WebsocketClient::PImpl { } ~PImpl() { - if (io_thread) { - io_thread->join(); - } + close( + websocketpp::close::status::going_away, + "WebsocketClient::PImpl destructor"); + io_threads.lock([](auto &ts) { + for (auto &t : ts) { + if (t.joinable()) { + t.join(); + } + } + ts.clear(); + }); } int set_state(State state) { @@ -334,6 +344,17 @@ struct WebsocketClient::PImpl { INFO("Websocket 'run' thread end. {}", snapshot()); } + void run_in_background(int num_threads) { + io_threads.lock([&](vector &ts) { + while (num_threads-- > 0) { + ts.emplace_back([&]() { + configure_current_thread(fmt::format("{}-io", config.name)); + run(); + }); + } + }); + } + void run_one() { try { client.run_one(); @@ -516,6 +537,10 @@ void WebsocketClient::connect() { me_->connect(); } void WebsocketClient::run() { me_->run(); } +void WebsocketClient::run_in_background(int num_threads) { + me_->run_in_background(num_threads); +} + void WebsocketClient::run_one() { me_->run_one(); } boost::asio::io_context *WebsocketClient::io_context() { diff --git a/src/lib/io/websocket/websocket_client.h b/src/lib/io/websocket/websocket_client.h index 4c4313f05..d7d4d7b07 100644 --- a/src/lib/io/websocket/websocket_client.h +++ b/src/lib/io/websocket/websocket_client.h @@ -27,6 +27,7 @@ class WebsocketClient { bool is_connected() const; boost::asio::io_context *io_context(); void run(); + void run_in_background(int num_threads = 1); void run_one(); OpenHandler &open_handler(); MessageHandler &message_handler();