Consider the following sample program in which a loop is running;
int main()
{
for (int i = 0; i<= 300; ++i) {
}
}
Pretty basic, now let’s suppose I want to print out the value of i every second:
cout << "i= " << i << "\n";
A simple loop like the following might suffice, where “elaspedTime” is a ficticious integer containing the number of seconds the program has been running magically updated by the OS:
int lastTime = 0;
while (true) {
if (elapsedTime > lastTime) { // Another second has passed
cout << "i= " << "\n";
lastTime = elapsedTime;
}
}
The ultimate goal here is to give an output like the following (assuming the loop ran exactly 100 times per second because it was on an old, slow CPU):
$ ./myprog
i= 100
i= 200
i= 300
These are simple functions and routines, despite this, I see no way to perform such an operation in a “classical” c++ program which typically has just a main() function. Despite the simplicity is this the point at which I need to learn multi-threading? Or, is it possible to call functions from main() and not wait for their return but without that called function “hogging” the thread?
What’s wrong with doing this? No multitasking required.