タイマー オブジェクトのベクトルがあります。各 Timer オブジェクトは、成長期間をシミュレートする std::thread を起動します。コマンドパターンを使用しています。
何が起こっているかというと、各タイマーが次々に実行されますが、私が本当に欲しいのは、1つが実行されることです....そして、一度終了すると、次のタイマーが....次のタイマーが終了すると...メインに干渉しませんプログラムの実行
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();
}
初めて完了します (「完了」のカウントが表示されます)が、EXEC_BAD_ACCESSで_t->execute();
内部でクラッシュします。for loop
ベクトルのサイズを確認するために cout を追加しましたが、2 であるため、両方のタイマーが内部にあります。コンソールにこれが表示されます:
this Timers * 0xbfffd998
_timers std::__1::vector<Timer *, std::__1::allocator<Timer *> >
すべてがクラッシュせずに完了するように変更するdetach()
と、それらのタイマーが終了するまでアプリの実行がブロックされます。join()