Han Yan
/
ms2b
not running
Diff: Car.cpp
- Revision:
- 0:3b4906b8a747
diff -r 000000000000 -r 3b4906b8a747 Car.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Car.cpp Tue Dec 10 22:29:09 2019 +0000 @@ -0,0 +1,61 @@ +#include "Car.h" +#include <stdlib.h> + +#define TICK 1000 + +Car::Car(int id, Road* road, int flag) { + this->id = id; + this->road = road; + this->flag = flag; + + cycle = 0; + + this->thread = NULL; +} + +void Car::update() { + bool crossed = false; + while (true) { + ThisThread::sleep_for(TICK); + road->go_flags.wait_all(flag); + cycle++; + + position = position + speed; + + if (cycle % 5 == 0) { + speed = rand() % 11 + 5; + } + + if (position < 54) { + speed = std::min(speed, 54 - position); + } else if (!crossed && position == 54) { + speed = 0; + crossed = true; + } else if (position < 56) { + speed = 1; + } + + road->done_flags.set(flag); + } +} + +void Car::reset(int position, int speed) { + road->done_flags.clear(flag); + + if (thread != NULL) { + thread->terminate(); + } + + thread = new Thread(); + thread->start( callback(this, &Car::update) ); + + cycle = 0; + this->position = position; + this->speed = speed; +} + +void Car::stop() { + if (thread != NULL) { + thread->terminate(); + } +} \ No newline at end of file