在循环中调用boost io_service poll
call boost io_service poll in a loop
我目前正在尝试使用boost::asio从循环中手动更新我的程序的一部分,如下所示:
class A
{
A::A() : m_io() {}
A::update()
{
m_io.poll();
//do other stuff
}
A::postSomething()
{
while(1)
{
m_io.post(...);
sleep(1000);
}
}
}
void main()
{
A a;
boost::thread thr(boost::bind(&A::postSomething, &a));
while(1)
{
a.update();
}
}
如果我运行程序,没有post()被处理。但是,如果我像这样在类成员update()中添加m_io.reset():
A::update()
{
m_io.poll();
//do other stuff
m_io.reset();
}
这似乎有效,但我仍然想知道这样做是否正确??我是否冒着因为reset()而丢失post()调用的风险?
谢谢。
下面是如何使用工作对象的演示:Live On Coliru
#include <iostream>
#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
class A
{
using ios = boost::asio::io_service;
ios m_io;
boost::optional<ios::work> m_active;
public:
A() : m_io(), m_active(ios::work(m_io)) {}
~A() {
m_active.reset();
m_io.run(); // to completion
}
void update()
{
m_io.poll();
//do other stuff
}
void postSomething()
{
int i = 0;
while(m_active)
{
m_io.post([&]{std::cout<<"something" << ++i << "n";});
boost::this_thread::sleep_for(boost::chrono::milliseconds(250));
}
}
};
int main()
{
boost::thread thr;
{
A a;
thr = boost::thread(boost::bind(&A::postSomething, &a));
for (int i = 0; i < 300; ++i)
{
boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
a.update();
}
}
thr.join(); // thread will not join unless A is destructed (m_active is cleared)
}
然而,你可能还想看看开发Boost Asio扩展,因为这将允许你"只run()
",仍然交错你自己的(大概是非io)任务
相关文章:
- 将继承的结构传递给 poll()
- 在librdkafka中,dr_cb在produce()线程或poll()线程上执行
- Windows Service 可以枚举桌面顶级窗口吗?
- bad_weak_ptr使用从 boost::asio::io_context::service 继承的类
- C++ API-MS-WIN-SERVICE-PRIVATE-L1-1-1.DLL依赖项问题
- 是否可以使用C /WinRT创建Windows Service应用程序
- 在使用 Poll() 的 TCP 服务器 - 客户端连接中,我是否需要手动设置事件?我从来没有到达 POLLOUT 来写
- QTimer with asio::io_service.poll_one() or poll()
- 如何在Linux上的C中使poll()立即退出
- Windows Service 无法调用 C++ 本机方法 [DllImpor( "myDLL" )]
- windows service SIGSEGV
- poll()是否预计需要40ms才能返回,即使数据会更快可用
- Singleton Service classes in c++
- poll()套接字编程tcp-linux多连接问题
- 以嵌套或递归方式(即在处理程序内)调用 asio io_service poll() 或 poll_one() 是否有效
- 来自 MSDN 的 InternetGetConnectedState 和"it should not be used from a service"声明
- C++ in the cloud. Casablanca REST Service on Microsoft Azure
- poll()系统在Linux中调用带有分段错误的核心转储
- Qt Web Service帖子查询
- poll()系统调用以及之后接收或发送数据的行为