C++ pause and resume while(true) loop

  • Context: C/C++ 
  • Thread starter Thread starter guest1234
  • Start date Start date
  • Tags Tags
    C++ Loop Resume
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 7K views
guest1234
Messages
38
Reaction score
1
How to design a class, that executes an infinite loop, but may be paused, resumed and stopped by user input? I'll give you an example

Code:
class Simulation {
public:
	void start(){
		m.init();
		while(!m.isFinished())
			m.update(); // computationally expensive calculation
	}
	void pause();
	void resume();
	void stop();
private:
	Model m;
};

int main() {
	Simulation s;
	s.start();
	// wait for user input
}

Now obviously s.start() takes up the whole program and there's now way of stopping it properly. It just doesn't have the chance to get user input.
What is the right way to do it? I assume that threads are needed but I have yet no idea how to use them here. Maybe creating a listener class and putting this and model to separate threads? Any help appreciated.
 
Last edited:
Physics news on Phys.org
Just start calculations in another thread with beginthread().

It will require some tricks, but AFAICT that's the only reasonable approach.
 
The answer to this problem depends on your environment. If threads are available, then you could use one thread to run the infinite loop and the other to process IO.

If threads are not available, you may have "signals". Or you may have "messages" which you have to read periodically.

Unless you specify more details, there is no definite answer.
 
See if your compiler / operating system supports a function like kbhit() which returns a status to indicate if there's a pending key stroke or not.