websocketpp
websocketpp copied to clipboard
why don't multi handling message_handler when multi io_context run
Hello When a new message happens while thread-1 do heavy work on on_message, thread-2 want to do new message using on_message. what can i do?
#include <iostream>
#include <vector>
#include <thread>
#include <string>
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/scoped_thread.hpp>
#include <boost/lexical_cast.hpp>
typedef websocketpp::client<websocketpp::config::asio_client> client;
class ptr;
void on_message(websocketpp::connection_hdl, client::message_ptr msg) {
std::string curTrId = boost::lexical_cast<std::string>(boost::this_thread::get_id());
std::printf("%s -> %s", curTrId.c_str(), msg->get_payload().c_str());
std::cout << msg->get_payload() << std::endl;
while(true){}; //heavy work
}
int main() {
std::vector<std::thread> _threads;
boost::asio::io_context _io_context;
boost::asio::io_context::work _work{_io_context};
for (unsigned n = 0; n != 4; ++n) {
_threads.emplace_back([&] {
_io_context.run();
});
}
std::string uri = "ws://localhost:1234";
client c;
c.set_access_channels(websocketpp::log::alevel::all);
c.set_error_channels(websocketpp::log::alevel::all);
c.init_asio(&_io_context);
c.set_message_handler(&on_message);
websocketpp::lib::error_code ec;
client::connection_ptr con = c.get_connection(uri, ec);
if (ec) {
std::cout << "could not create connection because: " << ec.message() << std::endl;
return 0;
}
c.connect(con);
while(true){c.run();}
}
Hi. Have you tried a yield() during the heavy load? If your heavy load is making blocking calls then this still may not help you. Another way would be offload the heavy load onto another thread, allowing on_message to return.
eg:
while(true){ std::this_thread::yield(); //heavy work };