gpt4 book ai didi

c++ - 如何在其他线程中运行 io_service?

转载 作者:行者123 更新时间:2023-11-28 05:39:48 26 4
gpt4 key购买 nike

我正在尝试运行 udp 服务器。问题是阻塞了 io_service 上的 run() 调用。所以我决定使用 boost bind 在其他线程上运行这个方法。结果主线程执行超出了 DictionaryImpl 构造函数范围,但是当我发送 udp 包时,tcpdump 告诉我我的端口无法访问。当我在主线程中调用 run() 调用 io_service 时,一切正常。问题出在哪里?

class DictionaryImpl  {
boost::asio::io_service io;
boost::scoped_ptr<boost::thread> thread;

public:
DictionaryImpl() {
try {
udp_server2 udpReceiver(io);

thread.reset(new boost::thread(
boost::bind(&DictionaryImpl::g, this, std::ref(io))));

} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
}

}

void g(boost::asio::io_service & io){
io.run();
}

virtual ~DictionaryImpl() {
if (!thread) return; // stopped
io.stop();
thread->join();
io.reset();
thread.reset();
}

};






class udp_server2
{
public:
udp_server2(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13003))
{
start_receive();
}

private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server2::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}

void handle_receive(const boost::system::error_code& error,
std::size_t /*bytes_transferred*/)
{
if (!error || error == boost::asio::error::message_size)
{
std::cout<<"handle_receive\n";
start_receive();
}
}



udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};

最佳答案

DictionaryImpl 的 io_service 会在用完工作时停止。您可以使用 asio::io_service::work 来防止这种情况。

~DictionaryImpl 中,您在 io_service 上调用 stop 之后调用 reset。只有在您计划随后重新启动 io_service 时,您才会这样做。

看起来你会从重新访问文档中受益(我承认它有点稀疏)。也可以看看 asio 文档中的多线程示例。他们将展示使用 work 对象的示例。

关于c++ - 如何在其他线程中运行 io_service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com