OK, I tried some code if it is what I want but GetAsyncKeyState(VK_SPACE) is not good. The reason is I have to hold space all the time until the loop cycle passes this function. It doesn't react to key press. |
GetAsyncKeyState only responds to keypresses when you call it.
If you're not calling it in the time-consuming loop, then it won't poll the keystate until that loop exits.
Now, I also searched a liitle bit and found signal library. When I press ctrl+c it does what I want (end the loop and execute the rest of the code after the loop). |
Ehhh.. I guess. I mean it is working exactly as you think it is, so I guess it's fine. But I don't know... for whatever reason this feels dirty to me. Maybe I'm just crazy. =P
Something like this could just as easily be accomplished with any kind of queued/buffered input. Like... a simple kbhit() call would probably work just as well without using signal handlers.
Although, I really don't fully understand what this signal does and why it reacts only on ctrl+c and not any key press. |
Ctrl+C sends a special "user wants to abort" signal to the program. By calling the 'signal' function, you're saying "I want to catch that signal and treat it differently from the default behavior".
This is not really something that is meant to be used for normal program flow, it's really to be reserved for when things go horribly, horribly wrong and the user has no choice but to forcefully abort.
I only wanted to ask you if it is "good and safe" way to do things (for example in code where I have dynamic arrays, in code which is composed of multiple classes, use file IO, ...) |
Safe? Yes, for the most part
Good? That's questionable.
The only thing that might be unsafe is that raiseFlag might be called by the signal handler from another thread (in fact, I'd imagine it'd have to be), which means you'd have to guard your flagLoop variable, either by making it atomic, or by putting access to it behind a mutex.
Does it have any effect on performance? |
I doubt it. Your thread is still blasting away running at full speed, and you're not really having it do any extra work, so I doubt this will impact performance.