How to stop linux timer? - linux

I have a requirement wherein I start a timer and will do a particular task for a certain time. Once the timer expires,I shall set a global variable in the handler. This variable is checked continuously by my process. The process stops once the global variable is set.
But the problem with setitimer as in its description is " When any timer expires, a signal is sent to the process, and the timer (potentially) restarts. "
How do I stop the timer in my handler?

From the getitimer(3p) man page:
Setting it_value to 0 shall disable a timer, regardless of the value of
it_interval.

Related

Python How to have OS block the process and resume on timer

I have been looking around and I can't seem to find a module that allows me to block the current process until the timer is done. What I don't want to do is utilize the CPU while waiting (busy waiting). I want the process to be blocked/suspended by the operating system and will be automatically notified when the timer is done.
# use a system call to create a waitable timer
timer = CreateWaitableTime()
# use another system call that waits on a waitable object
WaitFor(timer) # this will block the current process until the timer is signaled
# .. sometime in the future, the timer might expire and it's object will be signaled
# causing the WaitFor(timer) call to resume operation
do_other_stuff() # after timer
Edit
The reason for this is that I am going to have another process spawn this processes, therefore it doesn't matter if these get blocked. They need to be able to wait without wasting CPU time.
from threading import Event
evnt = Event()
wait_for = 5 #seconds
evnt.wait(wait_for) # will block for 5 seconds, or unless set early
another thread can call set to early finish the wait above
evnt.set()

What's the difference between Thread.Sleep() and Thread.SpinWait()

I have a WinForm application that uses a BackGroundWorker to create a TCP Client and send some data to a remote server.
When the socket finish close the connection and the BGW exits from the DoWork Sub.
In the RunWorkerCompleted Sub I must to wait a packet from the remote server, so I have always running a TCP server that fills a Friend String type variable and indicates that the whole packet is received using a Boolean type variable(flag).
So I must to wait that flag to becomes True to process the data that must be in the String type variable; but I don't want to hang up the GUI so I see that exist a method called SpinWait.
So, Can this code works?
There's any way to get out if the loop if the flag doesn't to true 5 minutes later?
Private Sub BGW1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGW1.RunWorkerCompleted
While Not AckReady
System.Threading.Thread.SpinWait(500)
End While
'Here process the received data from TCP server
TmrReport.Start()
End Sub
Another things is, How many iterations represent 500mS?
Per the documentation:
Thread.SpinWait Method
The SpinWait method is useful for implementing locks. Classes in the .NET Framework, such as Monitor and ReaderWriterLock, use this method internally. SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. The duration of the wait therefore depends on the speed of the processor.
Contrast this with the Sleep method. A thread that calls Sleep yields the rest of its current slice of processor time, even if the specified interval is zero. Specifying a non-zero interval for Sleep removes the thread from consideration by the thread scheduler until the time interval has elapsed.
So, Sleep basically releases the processor so it can be used by something else, whereas SpinWait runs a loop that keeps the processor busy (and locked to other threads).

How does libuv and Node.js actually schedule timers?

How does libuv and the operating system actually schedule timers like setTimeout and setInterval in Node.js? I see that no CPU is used by the node process until a timer fires. Does this mean the OS schedules the timer, and wakes up the Node process when the timer is fired? If so, how does an OS schedule a timer and how exactly does the hardware execute it?
Timer callbacks are executed as part of the NodeJS event loop. When you call setTimeout or setInterval, libuv (the C library which implements the NodeJS event loop) creates a timer in a 'min heap' data structure which is called the timers heap. In this data structure, it keeps track of the timestamp that each timer expires at.
At the start of each fresh iteration of the event loop, libuv calls uv__update_time which in turn calls a syscall to get the current time and updates the current loop time up to a millisecond precision. (https://github.com/nodejs/node/blob/master/deps/uv/src/unix/core.c#L375)
Right after that step comes the first major phase of the event loop iteration, which is timers phase. At this phase, libuv calls uv__run_timers to process all the callbacks of expired timers. During this phase, libuv traverses the timers heap to identify expired timers based on the 'loop time' it just updated using uv__update_time. Then it invokes the callbacks of all those expired timers.
Following is a redacted snippet from the event loop implementation in NodeJS to highlight what I just described.
while (r != 0 && loop->stop_flag == 0) {
uv__update_time(loop);
uv__run_timers(loop);
// ...redacted for brevity...
r = uv__loop_alive(loop);
if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
break;
}
I wrote a series of articles on NodeJS event loop some time back. I hope this article from that series would be helpful. https://blog.insiderattack.net/timers-immediates-and-process-nexttick-nodejs-event-loop-part-2-2c53fd511bb3
Node uses libuv underneath to take care of this. While setTimeout has some internal managing of its own, it ends up using the uv_timer_t facility provided by libuv.
Lets assume that the only thing the event loop is doing is the timer. libuv will calculate the poll timeout, which will actually be the timer's due time (in this example). Then the event loop will block for i/o by using the appropriate syscall (epoll_wait, kevent, etc). At that point it's up to the kernel to decide what to do, but the current thread of execution is blocked until the kernel wakes it up again, so there is no used CPU here, because nothing is happening.
Once the timeout expires, the aforementioned syscall will return, and libuv will process the due timers and i/o.

How to make WM_TIMER msg be called in ordered sequence in WinApi?

I'm doing winapi programming and i usually have a problems related to WM_TIMER msg: for example, when i put function that activates when WM_TIMER msg is called, like Update() function for example, this function is still called even though i killed timer. What's the main problem right now is that when i believe that i deleted the class that contain Update() function, this class still calls Update() function even though i killed timer and this class first, and because of this, i get memory error because this Update() function deals with attributes that are already deleted in previous delete function. Is there any solution to make WM_TIMER be called after certain task is done?
The WM_TIMER message is actually a flag -- when some timer expires, the flag is set to generate a single WM_TIMER event if the message queue is empty and GetMessage is called.
This avoids clogging up the system with many WM_TIMER messages and collapses multiple expired timers into one, but has the disadvantage of delivering the WM_TIMER message after all other messages (WM_PAINT is treated similarly).
So what you are seeing is that the timer you have killed has already elapsed and the flag is set, but the message will not be delivered until your program is otherwise idle.
You want to keep a flag to memorize whether you are actually waiting for a timer event.
In an application with multiple timers in parallel you'd keep a list of active timers, and use the Windows timer mechanism to schedule the next timer to elapse, and in the handler, invoke all sub-handlers whose deadlines are past.

Starting a sleeping thread in .NET

if a threadA is sleeping, how will another thread threadB call threadA to start ?
Please provide an example if possible.
Instead of sleeping you will want to create an EventWaitHandle and use WaitOne with a timeout.
When you want the thread to wake-up early, you will simply set the event to signaled.
First create the EventWaitHandle:
wakeUpEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
Then in your thread:
wakeUpEvent.WaitOne(new TimeSpan(1, 0, 0));
When the main program wants to wake up the thread early:
wakeUpEvent.Set();
Note: You can either set the event to auto reset or manual reset. Auto reset means once WaitOne returns from the event, it will set it back to non signaled. This is useful if you are in a loop and you signal multiple times.
A thread can be started by waiting on a WaitObject and having the other thread calling the Set method on it. Look at the WaitHandle.WaitOne method.
Here's article that may be of help as well.

Resources