我有一个计时器对象 vector 。每个计时器对象都会启动一个模拟生长期的 std::thread。我正在使用命令模式。
发生的情况是每个计时器都被一个接一个地执行,但我真正想要的是一个被执行......然后一旦完成,下一个......一旦完成下一个......同时不干扰与程序的主要执行
class Timer
{
public:
bool _bTimerStarted;
bool _bTimerCompleted;
int _timerDuration;
virtual ~Timer() { }
virtual void execute()=0;
virtual void runTimer()=0;
inline void setDuration(int _s) { _timerDuration = _s; };
inline int getDuration() { return _timerDuration; };
inline bool isTimerComplete() { return _bTimerCompleted; };
};
class GrowingTimer : public Timer
{
public:
void execute()
{
//std::cout << "Timer execute..." << std::endl;
_bTimerStarted = false;
_bTimerCompleted = false;
//std::thread t1(&GrowingTimer::runTimer, this); //Launch a thread
//t1.detach();
runTimer();
}
void runTimer()
{
//std::cout << "Timer runTimer..." << std::endl;
_bTimerStarted = true;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
_bTimerCompleted = true;
std::cout << "Growing Timer Finished..." << std::endl;
}
};
class Timers
{
std::vector<Timer*> _timers;
struct ExecuteTimer
{
void operator()(Timer* _timer) { _timer->execute(); }
};
public:
void add_timer(Timer& _timer) { _timers.push_back(&_timer); }
void execute()
{
//std::for_each(_timers.begin(), _timers.end(), ExecuteTimer());
for (int i=0; i < _timers.size(); i++)
{
Timer* _t = _timers.at(i);
_t->execute();
//while ( ! _t->isTimerComplete())
//{
//}
}
}
};
执行上面的代码:
Timers _timer;
GrowingTimer _g, g1;
_g.setDuration(BROCCOLI::growTimeSeconds);
_g1.setDuration(BROCCOLI::growTimeSeconds);
_timer.add_timer(_g);
_timer.add_timer(_g1);
start_timers();
}
void start_timers()
{
_timer.execute();
}
在 Timers::execute 中,我尝试了几种不同的方法来执行第一个而不是执行 接下来直到我以某种方式发出信号完成为止。
更新:
我现在这样做是为了执行一切:
Timers _timer;
GrowingTimer _g, g1;
_g.setDuration(BROCCOLI::growTimeSeconds);
_g1.setDuration(BROCCOLI::growTimeSeconds);
_timer.add_timer(_g);
_timer.add_timer(_g1);
//start_timers();
std::thread t1(&Broccoli::start_timers, this); //Launch a thread
t1.detach();
}
void start_timers()
{
_timer.execute();
}
第一次完成(我看到“已完成”cout),但在 for 循环
内的 _t->execute();
崩溃,并带有 EXEC_BAD_ACCESS。我添加了一个 cout 来检查 vector 的大小,它是 2,所以两个计时器都在里面。我确实在控制台中看到了这一点:
this Timers * 0xbfffd998
_timers std::__1::vector<Timer *, std::__1::allocator<Timer *> >
如果我将 detach()
更改为 join()
一切都会完成而不会崩溃,但它会阻止我的应用程序的执行,直到这些计时器完成为止。
最佳答案
为什么在这里使用线程? Timers::execute()
在计时器上调用 execute
,然后等待其完成,然后在下一个计时器上调用 execute
,依此类推。为什么不直接在 Timers::execute()
中调用计时器函数,而不是生成一个线程然后等待它呢?
线程允许您编写并发执行的代码。您想要的是串行执行,因此线程是错误的工具。
更新:在更新的代码中,您在后台线程上运行 start_timers
,这很好。但是,通过分离该线程,您可以让该线程运行到作用域的末尾。这意味着计时器对象 _g
和 _g1
甚至 Timers
对象 _timers
可能会在线程完成之前被销毁。完全的。考虑到计时器线程的耗时性质,以及您使用 detach
而不是 join
以避免代码阻塞的事实,这肯定是您的原因问题。
如果您在线程上运行代码,那么您需要确保该线程访问的所有对象都有足够长的生命周期,以便在线程访问它们时它们仍然有效。对于分离线程来说,这是特别难以实现的,因此不建议使用分离线程。
一种选择是沿着线程 t1
创建一个包含 _timers
、_g
和 _g1
的对象,并将其析构函数与线程连接。然后您需要做的就是确保对象一直存在,直到可以安全地等待计时器完成为止。
关于C++11 std::threads 并等待线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094510/