在我的项目中,每个类对象都有自己的线程,内部有无限循环 (while(1)),在其中执行特定的对象函数。我正在尝试改变这一点,以便每个对象都可以与计时器异步执行其功能。
基本上这就是它如何与具有无限循环的线程一起工作:
class obj
{
public:
obj();
~obj();
//custom functions and variables
int x;
int obj_action;
move();
wait();
}
obj()
{
obj_action=1;
//when constructing object, make its thread with infinite while cycle
boost::thread make_thread(boost::bind(&obj::obj_engine,this));
}
void obj::obj_engine()
{
while(true)
{
if (obj_action==1){move();}
else if (obj_action==2){wait();}
Sleep(1);
}
}
void obj::move()
{
x++;
obj_action==2;
}
void obj::wait()
{
Sleep(5000);
obj_action==1;
}
这个例子展示了 obj 类,它有构造函数、析构函数、几个变量和几个函数。 在构造对象(obj())时,创建了线程。线程包含一个函数“obj_engine”,它具有无限循环 (while(true))。在循环中有两个函数: 1. wait() - 让线程休眠 5 秒。 2. walk() - 简单的 x+1 这两个函数在结束后通过定义 obj_action 相互切换。
现在我想改成在构造和对象时异步执行move()函数,在move()函数之后异步执行wait()函数,反之。所以我不需要使用任何线程。
我希望这样的结果:
//constructing
obj()
{
asynchronous(walk());
}
walk()
{
x++
asynchronous(wait());
}
wait()
{
Sleep(5000);
asynchronous(walk());
}
我听说你可以用 boost::asio timers 做到这一点,但我真的不知道怎么做。 如果有人能告诉我怎么做,我将不胜感激。
最佳答案
给你:
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <iostream>
class obj {
public:
obj() : x_(0), t_(io_service_, boost::posix_time::seconds(5)) {
t_.async_wait(boost::bind(&obj::move, this));
io_service_.run();
}
void move() {
x_++;
std::cout << x_ << std::endl;
t_.expires_at(t_.expires_at() + boost::posix_time::seconds(5));
t_.async_wait(boost::bind(&obj::move, this));
}
private:
int x_;
boost::asio::io_service io_service_;
boost::asio::deadline_timer t_;
};
int main(int, char**) {
obj a;
while(true);
}
asio 教程基本上涵盖了您需要的一切:this tutorial shows you how to use an asynchronous timer , 和 this tutorial shows you how to reset your timer .
更新:
请使用上面的源代码而不是我最初的源代码 - 由于 io_service_.run()
的重复调用,每个 move
调用都会在另一个线程中调用一段时间后,您的应用程序会因此而崩溃。上面的代码修复了这个问题,并通过这样做摆脱了 wait
函数。
关于c++ - 从 boost::threads 到 boost::asio 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746484/