快速了解Boost.Asio 的多線程模型
Boost.Asio 有兩種支持多線程的方式,第一種方式比較簡單:在多線程的場景下,每個線程都持有一個io_service,并且每個線程都調(diào)用各自的io_service的run()方法。
另一種支持多線程的方式:全局只分配一個io_service,并且讓這個io_service在多個線程之間共享,每個線程都調(diào)用全局的io_service的run()方法。
每個線程一個 I/O Service
讓我們先分析第一種方案:在多線程的場景下,每個線程都持有一個io_service (通常的做法是,讓線程數(shù)和 CPU 核心數(shù)保持一致)。那么這種方案有什么特點呢?
1 在多核的機器上,這種方案可以充分利用多個 CPU 核心。
2 某個 socket 描述符并不會在多個線程之間共享,所以不需要引入同步機制。
3 在 event handler 中不能執(zhí)行阻塞的操作,否則將會阻塞掉io_service所在的線程。
下面我們實現(xiàn)了一個AsioIOServicePool,封裝了線程池的創(chuàng)建操作:
class AsioIOServicePool
{
public:
using IOService = boost::asio::io_service;
using Work = boost::asio::io_service::work;
using WorkPtr = std::unique_ptr<Work>;
AsioIOServicePool(std::size_t size = std::thread::hardware_concurrency())
: ioServices_(size),
works_(size),
nextIOService_(0)
{
for (std::size_t i = 0; i < size; ++i)
{
works_[i] = std::unique_ptr<Work>(new Work(ioServices_[i]));
}
for (std::size_t i = 0; i < ioServices_.size(); ++i)
{
threads_.emplace_back([this, i] ()
{
ioServices_[i].run();
});
}
}
AsioIOServicePool(const AsioIOServicePool &) = delete;
AsioIOServicePool &operator=(const AsioIOServicePool &) = delete;
// 使用 round-robin 的方式返回一個 io_service
boost::asio::io_service &getIOService()
{
auto &service = ioServices_[nextIOService_++];
if (nextIOService_ == ioServices_.size())
{
nextIOService_ = 0;
}
return service;
}
void stop()
{
for (auto &work: works_)
{
work.reset();
}
for (auto &t: threads_)
{
t.join();
}
}
private:
std::vector<IOService> ioServices_;
std::vector<WorkPtr> works_;
std::vector<std::thread> threads_;
std::size_t nextIOService_;
};
AsioIOServicePool使用起來也很簡單:
std::mutex mtx; // protect std::cout
AsioIOServicePool pool;
boost::asio::steady_timer timer{pool.getIOService(), std::chrono::seconds{2}};
timer.async_wait([&mtx] (const boost::system::error_code &ec)
{
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Hello, World! " << std::endl;
});
pool.stop();
一個 I/O Service 與多個線程
另一種方案則是先分配一個全局io_service,然后開啟多個線程,每個線程都調(diào)用這個io_service的run()方法。這樣,當某個異步事件完成時,io_service就會將相應的 event handler 交給任意一個線程去執(zhí)行。
然而這種方案在實際使用中,需要注意一些問題:
1 在 event handler 中允許執(zhí)行阻塞的操作 (例如數(shù)據(jù)庫查詢操作)。
2 線程數(shù)可以大于 CPU 核心數(shù),譬如說,如果需要在 event handler 中執(zhí)行阻塞的操作,為了提高程序的響應速度,這時就需要提高線程的數(shù)目。
3 由于多個線程同時運行事件循環(huán)(event loop),所以會導致一個問題:即一個 socket 描述符可能會在多個線程之間共享,容易出現(xiàn)競態(tài)條件 (race condition)。譬如說,如果某個 socket 的可讀事件很快發(fā)生了兩次,那么就會出現(xiàn)兩個線程同時讀同一個 socket 的問題 (可以使用strand解決這個問題)。
下面實現(xiàn)了一個線程池,在每個 worker 線程中執(zhí)行io_service的run()方法:
class AsioThreadPool
{
public:
AsioThreadPool(int threadNum = std::thread::hardware_concurrency())
: work_(new boost::asio::io_service::work(service_))
{
for (int i = 0; i < threadNum; ++i)
{
threads_.emplace_back([this] () { service_.run(); });
}
}
AsioThreadPool(const AsioThreadPool &) = delete;
AsioThreadPool &operator=(const AsioThreadPool &) = delete;
boost::asio::io_service &getIOService()
{
return service_;
}
void stop()
{
work_.reset();
for (auto &t: threads_)
{
t.join();
}
}
private:
boost::asio::io_service service_;
std::unique_ptr<boost::asio::io_service::work> work_;
std::vector<std::thread> threads_;
};
無鎖的同步方式
要怎樣解決前面提到的競態(tài)條件呢?Boost.Asio 提供了io_service::strand:如果多個 event handler 通過同一個 strand 對象分發(fā) (dispatch),那么這些 event handler 就會保證順序地執(zhí)行。
例如,下面的例子使用 strand,所以不需要使用互斥鎖保證同步了 :
AsioThreadPool pool(4); // 開啟 4 個線程
boost::asio::steady_timer timer1{pool.getIOService(), std::chrono::seconds{1}};
boost::asio::steady_timer timer2{pool.getIOService(), std::chrono::seconds{1}};
int value = 0;
boost::asio::io_service::strand strand{pool.getIOService()};
timer1.async_wait(strand.wrap([&value] (const boost::system::error_code &ec)
{
std::cout << "Hello, World! " << value++ << std::endl;
}));
timer2.async_wait(strand.wrap([&value] (const boost::system::error_code &ec)
{
std::cout << "Hello, World! " << value++ << std::endl;
}));
pool.stop();
多線程 Echo Server
下面的EchoServer可以在多線程中使用,它使用asio::strand來解決前面提到的競態(tài)問題:
class TCPConnection : public std::enable_shared_from_this<TCPConnection>
{
public:
TCPConnection(boost::asio::io_service &io_service)
: socket_(io_service),
strand_(io_service)
{ }
tcp::socket &socket() { return socket_; }
void start() { doRead(); }
private:
void doRead()
{
auto self = shared_from_this();
socket_.async_read_some(
boost::asio::buffer(buffer_, buffer_.size()),
strand_.wrap([this, self](boost::system::error_code ec,
std::size_t bytes_transferred)
{
if (!ec) { doWrite(bytes_transferred); }
}));
}
void doWrite(std::size_t length)
{
auto self = shared_from_this();
boost::asio::async_write(
socket_, boost::asio::buffer(buffer_, length),
strand_.wrap([this, self](boost::system::error_code ec,
std::size_t /* bytes_transferred */)
{
if (!ec) { doRead(); }
}));
}
private:
tcp::socket socket_;
boost::asio::io_service::strand strand_;
std::array<char, 8192> buffer_;
};
class EchoServer
{
public:
EchoServer(boost::asio::io_service &io_service, unsigned short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
doAccept();
}
void doAccept()
{
auto conn = std::make_shared<TCPConnection>(io_service_);
acceptor_.async_accept(conn->socket(),
[this, conn](boost::system::error_code ec)
{
if (!ec) { conn->start(); }
this->doAccept();
});
}
private:
boost::asio::io_service &io_service_;
tcp::acceptor acceptor_;
};
以上就是快速了解Boost.Asio 的多線程模型的詳細內(nèi)容,更多關于c++ Boost.Asio 多線程模型的資料請關注腳本之家其它相關文章!
相關文章
VC創(chuàng)建進程CreateProcess的方法
這篇文章主要介紹了VC創(chuàng)建進程CreateProcess的方法,涉及VC操作進程的基本技巧,需要的朋友可以參考下2015-05-05
C語言for循環(huán)嵌套for循環(huán)在實踐題目中應用詳解
初學C語言,常常遇到for循環(huán)中嵌套個for循環(huán),初學者對于這種形式總是一知半解,這次我就整理了常見的for循環(huán)嵌套for循環(huán)的題目,我們一起爭取一舉拿下這類題。學廢他們,以后再見到就不怕啦!每天都要學一點呀。加油,奮斗的我們2022-05-05
Qt物聯(lián)網(wǎng)管理平臺之實現(xiàn)告警短信轉(zhuǎn)發(fā)
系統(tǒng)在運行過程中,會實時采集設備的數(shù)據(jù),當采集到的數(shù)據(jù)發(fā)生報警后,可以將報警信息以短信的形式發(fā)送給指定的管理員。本文將利用Qt實現(xiàn)告警短信轉(zhuǎn)發(fā),感興趣的可以嘗試一下2022-07-07

