Interrupt a program (function, sleep or for)

Hi all.

I'm programming a realtime toll simulator.
For example, it has 5 payboxes and x cars will pass 1 hour. The program will show in real-time the number of cars on each paybox, and other infos. But during this simulation I need to make the user possible to interrupt it to open a MENU and when he choses what he wants, the simulations continues.

My only problem is how can I do this interrupt, since I'm using the Sleep(100) function in a for to verify if cars will arrive or exit the payboxes every 0,1sec.

Help me please :D
Depends on what you have so far...

I guess it's a thread. Then it's a good idea to provide a state for that thread:

enum EState { Running, Waiting, ... };

Further more provide member variables for that thread:
1
2
EState m_State;
bool m_Wait;


and a function

1
2
3
4
5
6
7
8
9
10
11
void thread::Wait(int ms)
{
  do
  {
    m_State = Waiting;
    Sleep(ms);
    ms = 100;
    m_State = Running;
  }
  while(m_Wait);
}


which you call whenever you want go to sleep

later you can do something like this:
1
2
3
4
5
6
7
8
...
m_Wait = true;
while(m_State != Waiting)
{
  Sleep(100);
}
...
m_Wait = false;


but like I said, it's just one way...
Last edited on
Thanks coder777, I havent seen Threads yet, so I didn't understand much.

My teacher said me to do this way:
1
2
3
4
5
6
char leitura()
{
       if (kbhit())	
              return getch();
       return '\0';
}

Inside main:
1
2
3
4
5
6
7
8
9
10
do
{
       switch(opcao)
       {
              case 'p': system("pause");
              break;
       }
       // Insert your code here //
       opcao = leitura();
} while (opcao != '0');


And it's working very well.
But I'm facing another problem now, I'm using this function to count millisecs:
1
2
3
4
5
void sleep ( clock_t  ms)
{
       clock_t fim = ( clock() + ms);
       while( fim > clock() );
}

And in main:
1
2
3
4
5
while(1)
{
       sleep(1);
       t++;
}


The problem with this function is that it counts ms right just sometimes.
I think it has something to do with CPU clock changes, because if I run this program alone, it counts very slow, but if I open firefox on Youtube, that requires more processing from CPU, my program counts millisecs exactly right.

Very weird, what Can I do to solve this?
Last edited on
Topic archived. No new replies allowed.