I have a application in which I have to sleep for a very short time (in order of few micro seconds ). Fortunately my Linux kernel 2.8.* supports high res timers.
I have 2 options to sleep now
nanosleep
select() with a timeout.
I choose to use select() as it is quite portable. Does select() use the normal kernel timers ( jiffies) or it uses the hi res timers ?
Can this provide sleep functionality in order of microseconds ?
Related
We have a long standing bug report in Boost.Thread where apparently thread sleeps will wake the computer from sleep on timer elapse (https://svn.boost.org/trac/boost/ticket/11368). This is apparently due to the new use of SetWaitableTimerEx() to implement coalescing timer support which we call with a REASON_CONTEXT like this:
REASON_CONTEXT default_reason_context={0/*POWER_REQUEST_CONTEXT_VERSION*/, 0x00000001/*POWER_REQUEST_CONTEXT_SIMPLE_STRING*/, (LPWSTR)L"generic"};
If timer firing is causing the PC to wake from sleep, it surely must have something to do with this REASON_CONTEXT value.
Can anyone here tell us what the appropriate value to use to not have the PC wake from sleep on timer expiry?
According to this document from Microsoft: Windows Timer Coalescing, page 8-9:
SetWaitableTimerEx has two new parameters: WakeContext and TolerableDelay. You use the WakeContext parameter only when you set a timer that can wake the system from a sleep state.
It looks like passing NULL for the WakeContext parameter is fine and it's the only way SetWaitableTimerEx will not wake the system. Timer coalescing should still work.
I tried it in Windows 10 and it seems to work correctly. It doesn't wake the system and also doesn't look like it's just calling SetWaitableTimer. It could be different in older versions of Windows though, I haven't tested.
how would one implement a C++ timer function which would act like:
void glutTimerFunc(unsigned int msecs,void (*func)(int value), value); but was purely WinAPI (or STL) stuff? I need it to not busy wait, though. It needs to call a function after X number of milliseconds Thank you for any/all help!
I've been looking at struct timeval tv; but I'm al little confused about how to actually implement it. It needs to be a drop in replacement for glutTimerFunc(). Thanks
Use Waitable Timers - SetWaitableTimer after calling CreateWaitableTimer
When the due time arrives, the timer is signaled and the thread that
set the timer calls the optional completion routine.
There is an example of what I think is your desired usage pattern here.
i'd like to make a daemon in Vala which only executes a task every X seconds.
I was wondering which would be the best way:
Thread.usleep() or Posix.sleep()
GLib.MainLoop + GLib.Timeout
other?
I don't want it to eat too many resources when it's doing nothing..
If you spend your time sleeping in a system call, there's won't be any appreciable difference from a performance perspective. That said, it probably makes sense to use the MainLoop approach for two reasons:
You're going to need to setup signal handlers so that your daemon can die instantaneously when it is given SIGTERM. If you call quit on your main loop by binding SIGTERM via Posix.signal, that's probably going to be a more readable piece of code than checking that the sleep was successful.
If you ever decide to add complexity, the MainLoop will make it more straight forward.
You can use GLib.Timeout.add_seconds the following way:
Timeout.add_seconds (5000, () => {
/* Do what you want here */
// Continue this "loop" every 5000 ms
return Source.CONTINUE;
// Or remove it
return Source.REMOVE;
}, Priority.LOW);
Note: The Timeout is set as Priority.LOW as it runs in background and should give priority to others tasks.
I have a fairly simple application which downloads files in a thread. This thread uses the WinINet APIs, and begins like so:
HINTERNET hInternet = InternetOpen(strUserAgent.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
DWORD dwFlags = INTERNET_FLAG_NO_UI | INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD;
HINTERNET hUrl = InternetOpenUrl(hInternet, m_strURL.c_str(), L"", 0, dwFlags, NULL);
However, if there is no internet connection, or the remote host is down, InternetOpenUrl will take a long time to time out and complete. While it is doing this - that is, only in the situation that it can't connect to the remote host - it will use between 80-100% of one CPU until it finally returns. This can often continue for a minute or so, because of the timeout delay setting. On one system, in spite of the timeout settings (noted below), this has continued for up to ten minutes.
How do I:
Avoid such massive CPU usage when it's just trying to connect?
Signal the thread to terminate if I want to shut down the app? Normally a timeout is fine, but if the app needs to close then it will wait on this thread to finish, which is spending lots of CPU doing very little inside InternetOpenUrl.
[Aside: Current timeout settings on my system, as revealed by InternetQueryOption:
INTERNET_OPTION_CONNECT_TIMEOUT: 60s
INTERNET_OPTION_RECEIVE_TIMEOUT: 30s
INTERNET_OPTION_SEND_TIMEOUT: 30s
Changing these would decrease the time before the method gave up and returned and so decrease the time spent using so much CPU, but might affect connecting - after all, the timeouts are there for a reason. This app can be used in odd connection situations, such as on board ship, where connecting could potentially be over satellite with high latency and take longer than a standard desktop internet connection. I do not know what reasonable timeouts would be. Also, there has to be a better method to avoid the CPU usage and terminate more quickly than simply shortening the timeouts.]
You can use WinInet in asynchronous mode. Not sure whether it solves CPU utilization issue but termination can be handled properly.
I think you can close the session handle returned from InternetOpen with InternetCloseHandle.
According to http://msdn.microsoft.com/en-us/library/aa384350(v=VS.85).aspx it will unblock any pending operation on that handle.
So basically if you keep InternetOpenUrl in a separate thread, you can still close the session handle from the parent thread(a seperate thread is not required if you are using it in async mode). You can set a status callback function for any resource cleanup.
If you want to set a different timeout, use InternetSetOption.
PS: Its been a while I've done anything with WinINet library, so I cannot guarantee that the above method will work.
What are the various ways that a timer can be set up using the Windows API. What are the pros and cons of each method?
I'm using MS DevStudio's C++.
There are two timer related functions on the Windows system: SetTimer and KillTimer (I know, the names are odd - CreateTimer and DestroyTimer would be more sensible, as in CreateWindow and DestroyWindow, but that is what is available).
SetTimer can function in one of two modes: the timer event can trigger a user defined callback or it can post a message to a window. The format of this function is:
timer_id = SetTimer (window, event_id, interval, callback);
To use a callback:
timer_id = SetTimer (NULL, NULL, interval_in_milliseconds, callback);
To get a WM_TIMER message to a window:
timer_id = SetTimer (window, event_id, interval_in_milliseconds, NULL);
In both cases, the calling thread needs to have a message queue as both variants issue a WM_TIMER message, the default handler calls the callback function.
Depending on the OS you're using the value of interval has upper and lower bounds. See the API documentation for more details.
To release the timer after you're finished with it do the following if you provided a window handle:
KillTimer (window, event_id); // event_id is important!
and if you used a callback:
KillTimer (NULL, timer_id);
A single window can have many timers associated with it, use a different event_id for each timer. Reusing an event_id stops the first instance of the timer without posting the WM_TIMER message.
Pros: fairly easy to use.
Cons: latency between interval end and processing of WM_TIMER message, resolution is large, requires a message processing loop.
Another method for handling timers is to use waitable timer objects. These don't require any message processing, don't use WM_TIMER or callbacks. As such, they're a bit more complex. Understanding the Windows event system will be helpful.
There are three types of timer objects: manual-reset, synchronisation and periodic; and there are four functions for handling the timer objects: CreateWaitableTimer, SetWaitableTimer, CancelWaitableTimer and CloseHandle (there is a fifth, OpenWaitableTimer but that is unlikely to useful to many people). There are also a set of functions required for notification of when a timer expires: WaitForSingleObject, MsgWaitForSingleObject, WaitForMultipleObjects and MsgWaitForMultipleObjects being the most useful.
The usual method for using these timers is:
CreateWaitableTimer (...)
SetWaitableTimer (...)
WaitForSingleObject (...)
CloseHandle (...)
Compare this to SetTimer - the only way to know if a timer has expired is to poll it, either in a loop or with an infinte timeout (i.e. suspend the thread until the timer elapses).
Pros: very flexible, no need to have a message queue.
Cons: hard to use
Usually, look at the API you are going to use, for example MFC, Qt or GTK; they all have timer classes.
If you're not going to use a GUI API, I personally like boost::timer (www.boost.org)
For high resolution timers, use queryperformancecounter