Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-reentrant C# timer

I'm trying to invoke a method f() every t time, but if the previous invocation of f() has not finished yet, wait until it's finished.

I've read a bit about the available timers but couldn't find any good way of doing what I want, save for manually writing it all. Any help about how to achieve this will be appreciated, though I fear I might not be able to find a simple solution using timers.

To clarify, if t is one second, and f() runs the arbitrary durations I've written below, then:

Step  Operation    Time taken
1     wait         1s
2     f()          0.6s
3     wait         0.4s (because f already took 0.6 seconds)
4     f()          10s
5     wait         0s (we're late)
6     f()          0.3s
7     wait         0.7s (we can disregard the debt from step 4)

Notice that the nature of this timer is that f() will not need to be safe regarding re-entrance, and a thread pool of size 1 is enough here.

like image 335
Oak Avatar asked Jun 06 '10 19:06

Oak


People also ask

What is non reentrant function in C?

Non-reentrant functions are functions that cannot safely be called, interrupted, and then recalled before the first call has finished without resulting in memory corruption.

What does reentrant mean in C?

In computing, a computer program or subroutine is called reentrant if multiple invocations can safely run concurrently on multiple processors, or on a single processor system, where a reentrant procedure can be interrupted in the middle of its execution and then safely be called again ("re-entered") before its previous ...

Why malloc () is not a reentrant function?

On most systems, malloc and free are not reentrant, because they use a static data structure which records what memory blocks are free. As a result, no library functions that allocate or free memory are reentrant. This includes functions that allocate space to store a result.

Is printf re-entrant?

printf isn't re-entrant because it modifies a global variable i.e. the content of the FILE* stout.


1 Answers

Use a System.Threading.Timer. Initialize it with a period of Timeout.Infinite so it acts like a one-shot timer. When f() completes, call its Change() method to recharge it again.

like image 73
Hans Passant Avatar answered Sep 21 '22 07:09

Hans Passant