c++ structure: repeat set of functions at a certain time rate

谁说我不能喝 提交于 2019-12-08 09:14:40

问题


So I'm stuck with a little c++ program. I use "codeblocks" in a w7 environment.

I made a function which shows a ASCII map and a marker. A second function updates the markers position on that map.

I would like to know how I could make my main structure so that the marker gets updated and the map showed, and this repeated at a certain time rate. Which functions can I use to make this happen. What strategy should I follow?

every x times/second DO { showmap(); updatePosition();}

I am a c++ beginner and I hope you can help!


回答1:


A loop with usleep

unsigned XtimesPerSecond = 5;    // for example
unsigned long long microseconds = 1000000 / XtimesPerSecond;

do
{
    showmap();
    updatePosition();
    usleep(microseconds);
} while(true);



回答2:


Depending on what else your program needs to be doing, you may need to employ event driven programming. If updating that marker is the only thing it will be doing, a simple while loop with a sleep will suffice, as demonstrated in other answers.

In order to do event driven programming you generally need an event loop - which is a function that you call in main, which waits for events and dispatches them. Most event loops will provide timer events - where, basically, you ask the event loop to call function X after a given time interval elapses.

You most likely don't want to write your own event loop. There are many choices for an event loop, depending on many things like programming language and required portability.

Some examples of event loops:

  • the Qt event loop,
  • the GLib event loop,
  • the Windows event loop, and many more...



回答3:


Seems that you want to implement an infinite loop like games engine does.

Try to do this:

while (true)
{
    showmap();
    updatePosition();
    sleep(1);
}


来源:https://stackoverflow.com/questions/7956239/c-structure-repeat-set-of-functions-at-a-certain-time-rate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!