luacoder
luacoder

Reputation: 209

Non-blocking sleep timer in C

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

Answers (5)

Toonie
Toonie

Reputation: 33

Does the solution in this question, answer yours?

Timer to implement a time-out function

Regards, Toonie.

Upvotes: 0

Zuljin
Zuljin

Reputation: 2640

On Windows you have following options:

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

anijhaw
anijhaw

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

Mark Wilkins
Mark Wilkins

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

Martin Stone
Martin Stone

Reputation: 13007

The Win32 API has SetTimer(). There are code examples linked from that page.

Upvotes: 0

Related Questions