Add run_in_background fn to WebsocketClient (cpp)
This commit is contained in:
1 parent
e7e334fb5a
commit
21d9435a67
2 files changed
+30
-4
No files matched your search
@@ -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<CloseHandler> close_handler;
|
||||
size_t sub_id_counter{0};
|
||||
string server_name;
|
||||
optional<thread> io_thread;
|
||||
optional<thread> ping_thread;
|
||||
utils::LockBox<vector<thread>> 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<thread> &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() {
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user