[英]c++ error: use of deleted function boost::asio::io_context::io_context
[英]C++ how to run 2 boost:asio: io_context at the same time
我有 2 個boost::asio::io_context
變量,一個用於我的樹莓派和我的 arduino 之間的連接,另一個用於樹莓派和客戶端之間通過 tcp 服務器的連接。 我已經分別測試了兩個連接,它們工作得很好。 但是,當我嘗試加入他們時,它不起作用。 我知道通過制作兩個io.run,第二個永遠不會進入,因為程序會卡在第一個,所以我怎樣才能在io_context.run()中插入io.run?
我的主要內容如下:
boost::asio::io_context io_context;
boost::asio::io_context io;
int main{
//create a server object to accept incoming client connections
tcp_server server(io_context);
open_port_arduino();
start = std::chrono::high_resolution_clock::now(); //time_init
//writes to arduino with intervals of 2 seconds
tim.expires_after(boost::asio::chrono::seconds {2});
tim.async_wait(timer_handler);
//reads from arduino
start_read_arduino();
io.run();
io_context.run();
}
要回復您的評論:您不需要第二個 io_context。
但是,您可以(另請參閱Do we need multiple io_service per thread for threaded boost::asio server with a single acceptor and https://theboostcpplibraries.com/boost.asio-scalability )。
一個好處可能是線程隔離:如果您在單獨的線程上運行單獨的上下文,則存在隱式任務序列化。 (與多個線程上的單個上下文形成對比,其中任務可能需要手動序列化,例如使用鏈)。
我想你要“修復”的最直接的事情就是簡單地將對同一 io_service 的引用傳遞給各方:
static io_context io;
struct tcp_server {
tcp_server(io_context& ctx) : _ctx(ctx) {}
private:
io_context& _ctx; // REFERENCE
};
int main() {
tcp_server server(io);
// ...
(現場演示按預期打印“定時器回調:成功”)
如果您的某些 IO 任務阻塞很長時間,您將需要運行多個線程。 在這種情況下,我會切換將執行程序傳遞給您的類的方法,並確保它們將其包裝成股:
boost::asio::thread_pool io(2); // two threads
using boost::asio::any_io_executor;
struct tcp_server {
tcp_server(any_io_executor ex) : _ex(make_strand(ex)) {}
private:
any_io_executor _ex;
};
接着
int main() {
//create a server object to accept incoming client connections
tcp_server server(io.get_executor());
再次,現場演示按預期打印“計時器回調:成功”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.