簡體   English   中英

Boost C ++線程

[英]Boost C++ thread

我已經從構建了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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM