Reputation: 209
I'm looking for a good non-blocking sleep timer in C for windows.
Currently I am using sleep(10);
which of course is a blocking timer.
Also I want it to consume no system resources, like my sleep timer it doesn't use any CPU or system resources which I am happy with.
So, what is the best non-blocking sleep timer I could use? And please also include an example of how to use it.
Thanks.
Upvotes: 7
Views: 12990
Reputation: 33
Does the solution in this question, answer yours?
Timer to implement a time-out function
Regards, Toonie.
Upvotes: 0
Reputation: 2640
On Windows you have following options:
SetTimer - for GUI applications. Resolution around 15 milliseconds.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx
WaitableTimer - for non GUI application. You can wait for expiration
of this timer using WaitFor.... kind of functions or timer could run
callback function. Resolution around 15 milliseconds.
http://msdn.microsoft.com/en-us/library/ms687008(v=VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms686898(v=VS.85).aspx
Timer Queues - use this technique if you need to handle many timers. I think this timer could be more accurate than 15 ms. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687003(v=vs.85).aspx
Multimedia Timer - most accurate timer with 1 ms resolution. Unfortunately there is limit of those timers. I think 16 is max number. http://msdn.microsoft.com/en-us/library/windows/desktop/dd757664(v=vs.85).aspx
You should also remember that timer callback function will be run under different thread that your application. So if callback function use the same data as your main thread then you need to protect them (using Mutex, CriticalSection etc.) to eliminate simultaneous access by multiple threads.
Upvotes: 1
Reputation: 9402
You dont need an API you need to change your design.
A simple one is this.
You can have multiple threads, One is the Manager Thread and other are Worker Threads. At every 10 seconds the manager thread will wake up create a new worker thread and go to sleep. The worker threads will keep working even when the Manager is sleeping and this you have your non blocking effects.
I dont know how familar you are with threads, but here is a very very basic tutorial, that might get you started with this.
Upvotes: 6
Reputation: 41222
Based on the OP's recent comment to questions, it sounds as if the goal is to allow the program to continue processing but be able to call some function every 10 seconds. One way of providing this functionality would be to create a separate thread whose responsibility is to execute some function every 10 seconds. It could use Sleep( 10000 )
to block itself, then call the function, then sleep, etc.
The main thread would not be blocked in this case and could continue doing its work.
Upvotes: 0
Reputation: 13007
The Win32 API has SetTimer(). There are code examples linked from that page.
Upvotes: 0