Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ pause and resume while(true) loop

  1. Dec 26, 2013 #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 (Text):
    class Simulation {
        void start(){
                m.update(); // computationally expensive calculation
        void pause();
        void resume();
        void stop();
        Model m;

    int main() {
        Simulation s;
        // 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: Dec 26, 2013
  2. jcsd
  3. Dec 26, 2013 #2


    User Avatar

    Staff: Mentor

    Just start calculations in another thread with beginthread().

    It will require some tricks, but AFAICT that's the only reasonable approach.
  4. Dec 29, 2013 #3
    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.
  5. Dec 29, 2013 #4


    User Avatar
    Homework Helper

    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.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook