我正在使用这样配置的多线程 websocketpp 服务器:
Server::Server(int ep) {
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
Server::wspp_server.clear_access_channels(websocketpp::log::alevel::all);
Server::wspp_server.init_asio();
Server::wspp_server.set_open_handler(bind(&Server::on_open, this, _1));;
Server::wspp_server.set_close_handler(bind(&Server::on_close, this, _1));
Server::wspp_server.set_message_handler(bind(&Server::on_message, this, _1, _2));
try {
Server::wspp_server.listen(ep);
} catch (const websocketpp::exception &e){
std::cout << "Error in Server::Server(int): " << e.what() << std::endl;
}
Server::wspp_server.start_accept();
}
void Server::run(int threadCount) {
boost::thread_group tg;
for (int i = 0; i < threadCount; i++) {
tg.add_thread(new boost::thread(
&websocketpp::server<websocketpp::config::asio>::run,
&Server::wspp_server));
std::cout << "Spawning thread " << (i + 1) << std::endl;
}
tg.join_all();
}
void Server::updateClients() {
/*
run updates
*/
for (websocketpp::connection_hdl hdl : Server::conns) {
try {
std::string message = "personalized message for this client from the ran update above";
wspp_server.send(hdl, message, websocketpp::frame::opcode::text);
} catch (const websocketpp::exception &e) {
std::cout << "Error in Server::updateClients(): " << e.what() << std::endl;
}
}
}
void Server::on_open(websocketpp::connection_hdl hdl) {
boost::lock_guard<boost::shared_mutex> lock(Server::conns_mutex);
Server::conns.insert(hdl);
//do stuff
//when the first client connects, start the update routine
if (conns.size() == 1) {
Server::run = true;
bool *run = &(Server::run);
std::thread([run] () {
while (*run) {
auto nextTime = std::chrono::steady_clock::now() + std::chrono::milliseconds(15);
Server::updateClients();
std::this_thread::sleep_until(nextTime);
}
}).detach();
}
}
void Server::on_close(websocketpp::connection_hdl hdl) {
boost::lock_guard<boost::shared_mutex> lock(Server::conns_mutex);
Server::conns.erase(hdl);
//do stuff
//stop the update loop when all clients are gone
if (conns.size() < 1)
Server::run = false;
}
void Server::on_message(
websocketpp::connection_hdl hdl,
websocketpp::server<websocketpp::config::asio>::message_ptr msg) {
boost::lock_guard<boost::shared_mutex> lock(Server::conns_mutex);
//do stuff
}
我启动服务器:
int port = 9000;
Server server(port);
server.run(/* number of threads */);
添加连接时唯一的实质性区别在于消息发射 [ wssp.send(...)
]。越来越多的客户端并没有真正为内部计算增加任何东西。只有要发出的消息量才会增加。
我的问题是,无论我使用 1 个或多个线程,CPU 使用率似乎都没有太大差异。
server.run(1)
我用or启动服务器并不重要server.run(4)
(都在 4 核 CPU 专用服务器上)。对于类似的负载,CPU 使用率图表显示的百分比大致相同。我期望使用 4 个并行运行的线程来降低使用率。我想错了吗?
在某些时候,我感觉到并行性确实比发射更适用于聆听部分。因此,我尝试将其封闭send
在一个新线程(我分离)中,因此它独立于需要它的序列,但它并没有改变图表上的任何内容。
我不应该看到 CPU 产生的工作有什么不同吗?否则,我做错了什么?为了强制从不同的线程发出消息,我是否还缺少另一个步骤?