提升 ASIO 并隐藏那些棘手的 io_service 对象
所以,我有这门课。它应该是一个单身人士,但你没有理由不能做更多。
其中有两个线程。 一种是 io_service->run() 等待传入的 UDP 数据包。 另一个用于发送广播。
我按照这里的例子: http://www.boost.org /doc/libs/1_46_1/doc/html/boost_asio/example/echo/async_udp_echo_server.cpp
它有效 伟大的。唯一的问题是我不想在外部提供 io_service ,而是将其隐藏在类内部。
我还没有阅读所有 io_service 文档,但是对象实例中是否可以有一些私有版本的 io_service ? Socket 的构造函数使完成此任务变得极其困难。
您将如何更改示例以隐藏线程内的内容?
我也是一个 C++ 菜鸟 :P
So, I have this class. It should be a singleton, but there's no reason you couldn't make more.
In it, there are two threads.
One is for io_service->run() to wait for incoming UDP packets.
The other is for sending out broadcasts.
I followed the example here:
http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/echo/async_udp_echo_server.cpp
It works great. The only problem is that I don't want to have to provide the io_service externally, and instead have it hidden away inside of the class.
I haven't read through all the io_service documentation yet, but is it possible to have some private version of io_service within an object instance? Socket's constructor makes life incredibly difficult for getting that done.
How would you change the example to hide things inside the thread?
I'm also a huge C++ noob :P
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的!与我一起工作的人继承了这个可怕的库并解决了我的问题...
在类中隐藏 io_service 绝对是可能的,但是!您必须在套接字对象之前定义io_service 对象。指定子构造函数的顺序并不重要。
示例:
所以,这就是导致我的问题的原因。
Okay! Someone I work with inherited this horrible library and figured out my problem...
Hiding io_service within the class is absolutely possible BUT! You must have the io_service object defined before the socket object. It doesn't matter what order you specify the sub-constructors at all.
Example:
So, that's what caused my problem.
您可以隐藏 io_service ,但这没有多大意义。如果您决定采用异步模型,那么您必须全力以赴。因此,您的应用程序应该围绕 io_service 构建。也就是说,如果您将
io_service
隐藏在包装套接字的类中,那么谁将在io_service
上调用run ()
?更复杂的是,您需要为每个套接字类抛出一个额外的线程等。实际上可能适用于此类设计的一种可能的解决方案是拥有一些隐藏的单例io_service
,每个套接字类都在其中您的库将访问,但随后您限制用户跨多个线程扩展它。至于构造函数和很难获得正确的顺序,请查看 基于这个习语,它就是为了解决这类问题而设计的。You can have
io_service
hidden but that won't make much sense. If you decide to go with asynchronous model then you have to go for it all the way. Thus, your application should be built aroundio_service
s. That said, if you hideio_service
inside a class wrapping your socket then who is going to callrun ()
onio_service
? To complicate it even more, you will need to throw an extra thread per socket class etc. One possible solution that might actually work for that sort of design is to have some hidden singletonio_service
that every socket class in your library will access, but then you limit user from scaling this across multiple threads. As for the constructor and a hard time getting the order right, take a look at base from this idiom, it was designed to solve this kind of problems.