new thread to execute Sleep()

When I use Sleep(ms), my main function freezes, is there a way to execute Sleep() parallel to my main funtion? I'm a complete c++ rookie, so be easy on me :)
strange, are you using windows? i use Sleep() and it works just fine, it freezes like its supposed to.
It's basicly the same problem this guy has:
http://www.cplusplus.com/forum/beginner/1795/
but without all the lua things

questions:
- will making a new thread solve my problem?
- how do i make a simple new thread
Last edited on
If your ms is a negative number Sleep will lock up and freeze. Possibly put before the Sleep() call do:
1
2
3
4
if(ms > 1)
{
    Sleep(ms);
}
with freezing I mean the sleeping time. Everything works as it suppose to work, but I don't want my main function to freeze.

For example, I have a loop in my main function, with an integer that adds +1 every cycle. Now as soon as I press a hotkey, it has to sleep 10 seconds, but the loop function has to keep adding +1 while it's sleeping. After 10 seconds it has to give me the final value of the integer. But I can't get it to work, because Sleep() freezes the whole application.
You can do it all in a single thread. When the keypress comes in, set a timer, keep doing your adding and at the end of the loop check if 10 seconds have passed. You don't need to put the thread to sleep.

If you choose, to use a thread, then it's best to keep the main thread interactive and let worker threads do timing etc, but your problem is stated the other way around.
Thanks everyone, I'm gonna try to make it work :)
It sounds like a flawed approach. Sleep doesn't do what you think it does. It is not going to help you if you need accurate timing. Sleep causes the thread to stop executing for "AT LEAST" the amount of time that you specify. When the time expires the thread becomes eligible to execute again but that doesn't mean it will start running in exactly 10 seconds or whatever.

Of course sleep will cause the whole application to stop running if there is only 1 thread. That is the purpose of sleep. It will stop the thread that calls the function for at least the amount of time specified. I don't have the slightest idea what your program's purpose is so I can't really offer any solutions.
Topic archived. No new replies allowed.