In connection with my Dash Bolder Project or any game programming it is important to handle different actions independently and in a certain time beat. For example: read keyboard input every 200 miliseconds, calculate frames every 500 seconds, move enemies every 1000 seconds and so.
Coding threads can be quit challenging, so I decided to write my own thread classes.
Here it is!
Unit test successfull:
Task 1 runs every second and ends after 5 iterations
Task 2 runs every 2 seconds and ends after 10 iterations
class MyThread_Tasks : public MyThread {
private:
MyThread_Task1 task1;
MyThread_Task2 task2;
public:
MyThread_Tasks () : MyThread () {
boRunning = true;
milliseconds = 500;
}
void Execute () {
if (!boRunning)
return;
if (IsTimerFinished()) {
if (!task1.boRunning && !task2.boRunning) {
boRunning = false;
std::cout << "Tasks finished!" << endl;
return;
}
task1.Execute();
task2.Execute();
}
}
};
// the main routine shrinks to:
int main(){
MyThread_Tasks tasks;
while (tasks.boRunning)
tasks.Execute();
return 0;
}
It seems these technique are the basics of a multi-user-system with multible tasks in each user context...
Loops with "while, do-until, for" are in this case forbidden of certainly because of the democratic system. The code has to be written in an other way without loopings.
class MyThread_Task : public MyThread {
public:
int x;
int xStart;
int xEnd;
public:
MyThread_Task (int paStart, int paEnd) : MyThread () {
xStart = paStart;
xEnd = paEnd;
x = xStart;
boRunning = true;
milliseconds = 50;
}
// This function contains the for-loop as an iteration.
void Execute () {
if (!boRunning)
return;
if (IsTimerFinished()) {
doSomething(x);
x ++;
if (x >= xEnd) {
boRunning = false;
return;
}
TimerExecute();
}
}
};
int main (void) {
MyThread_Task task(1,10);
while (task.boRunning)
task.Execute();
}