提升C++线程

Boost C++ thread

本文关键字:线程 C++ 提升      更新时间:2023-10-16

我从以下位置构建了 server3 示例:

http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/examples.html

我唯一做的——修改了request_handler.cpp

// Decode url to path.
std::string request_path;
if (!url_decode(req.uri, request_path))
{
    rep = reply::stock_reply(reply::bad_request);
    return;
}
// Request path must be absolute and not contain "..".
if (request_path.empty() || request_path[0] != '/'
  || request_path.find("..") != std::string::npos)
{
    rep = reply::stock_reply(reply::bad_request);
    return;
}
// Fill out the reply to be sent to the client.
rep.status = reply::ok;
std::string filename = "/tmp/test.mp4";
std::ifstream file (filename.c_str(), std::ios::in|std::ios::binary);
char buf[1024000]; // 1MB Buffer read
while (file.read(buf, sizeof(buf)).gcount() > 0)
       rep.content.append(buf, file.gcount());
rep.headers.resize(9);
rep.headers[0].name = "Content-Length";
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
rep.headers[1].name = "Content-Type";
rep.headers[1].value = "video/mp4";

当我打开chrome并点击服务器时,我可以获取视频,没有问题。同时,我打开另一个选项卡并点击服务器时,没有任何反应。看起来它等到第一个选项卡完成。

目标是拥有一个处理多个连接并发送多个文件的服务器..

服务器的响应能力将基于以下内容:

  • 您使用阻止磁盘 IO 调用,因此这将在读取数据时挂起线程。 为了获得最佳性能,您希望尽可能多地使用非阻塞。
  • 运行的线程数 io_service::run()。

对您来说,最简单的方法很可能是运行更多运行 io_service::run() 的线程。 我的猜测是你只运行一个线程,这就是为什么在第一个选项卡完成之前你在第二个选项卡中没有得到任何响应的原因。

更好的解决方案是考虑使用非阻塞磁盘io。