I need to execute two while loops at exactly the same time.
One while loop (A) is a timeout,
the other one (B) is the actual code which need to check things.
So, A works like this:
I've putted an integer with the value of 20 into a while loop, every time the integer gets dropped by one (20, 19, 18, 17,...), if that integer finally hits zero; it returns a value saying "false", so B terminates. Because B only runs when the value is true.
Pseudo code:
1 2 3 4 5 6 7 8 9 10 11 12
bool bool1 = true;
int int1 = 20;
while (bool1) {
while (bool1) {
int1--;
sf::sleep(1); //SFML library for timeout of one second,
if (int1 == 0) {
bool1 = false;
}
}
/*----------ACTUAL CODE BENEATH THIS LINE----------*/
}
The while-loop indeed stops; but the 'actual code' isn't terminated.
How can I do this?
As you are already using SFML perhaps you can look at sf::Thread. This allows you to launch "parallel" processes which sounds like what you wish to accomplish.
I don't think threads are what I'm looking for.
I'd have to work with different functions, and because you can't go from void to main, and variables ain't global,... I'd encounter to much problems.
I don't think threads are what I'm looking for.
I'd have to work with different functions, and because you can't go from void to main, and variables ain't global,... I'd encounter to much problems.
The user has a few seconds to quit my application.
For that I use the SFML keyboard-events, the user only has a few seconds to press 'quit'.
Threads would work in theory, but it'd get messy with my variables etc. If I could declare variables globally in each function it'd be okay to work with threads. And jumping from function to main again also.
The problem with your example is that the "CODE BENEATH THIS LINE" won't ever be evaluated until the first while loop goes all the way through the timeout. The code in the loops cannot run concurrently unless you employ threads, which you stated would add a higher degree of complexity to your code.
bool bool1 = true;
int int1 = 20;
while (bool1) {
while (bool1) {
int1--;
sf::sleep(1); //SFML library for timeout of one second,
if (int1 == 0) {
bool1 = false;
}
}
if (!bool1) {
/*----------ACTUAL CODE BENEATH THIS LINE----------*/
}
}
Alternative:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for (int timeout = 20; timeout > 0; timeout--) {
sf::sleep(1); //SFML library for timeout of one second,
///////////////////////////////////////////////////////////////////////////
// logic to get user input from keyboard and quit if necessary. //
// set timeout to 0 if user decides to quit //
///////////////////////////////////////////////////////////////////////////
if (timeout == 1) {
/*----------ACTUAL CODE BENEATH THIS LINE----------*/
timeout = 21;
}
}