implement Windows timer - windows

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.

Related

How to get OUT of an ISR in freertos / esp-idf

I have an ISR that's fired from a button press. The handler looks like this...
void IRAM_ATTR buttonIsrHandler(void *arg) {
xTaskResumeFromISR(buttonTaskHandle);
}
// `buttonTaskHandle` is set up as the handle for this task function...
void buttonTask(void *pvParameter) {
while (1) {
vTaskSuspend(NULL);
// ... my task code goes here...
}
}
When I'm in an ISR, I can't do certain things. For instance, calling ESP_LOGI() results in an error relating to disallowed memory access.
I was expecting those limitations to exist only within the buttonIsrHandler() function, but they also exist within buttonTask() given that I woke it up from an ISR.
How do I get out of an ISR so that I can do all my normal stuff? I could use something like a queue to do this, but that seems heavy weight. Is there an easier way? Would sending a task-notification from the ISR handler be any different? Any other suggestions?
As you can see in the documentation of xTaskResumeFromISR, such a use case is not recommended. Task notifications are designed and optimized for this exact use case. In your case, you'd want to use vTaskNotifyGiveFromISR.
As for "leaving the ISR", FreeRTOS will not call your task function from the ISR context. xTaskResumeFromISR and other functions simply update the state of the task so that it can run when its turn comes.

OSX Objective C BOOL/vars thread safe?

Simple Question... is a global BOOL thread safe for me to use for thread synchronization?
What other data types are actually safe, e.g. long longs..?
Eg:
I have a task that runs - only want it to run once concurrently.
<pre>
BOOL isRunning;
unsigned long long progress;
if(!isRunning){
dispatch_async(secondaryTask,^{
[self doWork];
});
-(void)doWork
{
isRunning=TRUE;
do a long op
isRunning=FALSE;
}
</pre>
For the atomic types, exactly the same rules as ordinary C apply. So there's no guarantee of thread safety on any of them.
Use OSAtomic, NSConditionLock, the NSLocking protocol, serial dispatch queues, individual runloops, memory fences, spin locks, etc, to achieve thread safety.
For the trivial code given, which I accept is probably just for exposition, you'd most likely provide a completion handler block, which the asynchronous block would dispatch upon completion. If it's a serial queue, just push the task to it. Consider a dispatch group if you want synchronisation points within concurrent task groups.

boost.asio. The possibility to expect the completion of any object in queue is necessary

In asio:: io_service I insert objects. asio:: io_service::run() runs in several threads.
The possibility to expect the completion of any object in queue is necessary.
For example:
template <typename T>
struct handler {
void operator()() {
....
}
T get() const {...}
};
asio::io_service ios;
ios.post(handler());
How I can refer to the object in queue?
How can I pause the main program loop, untill handler::operator() is executed?
Thanks.
Here's what I know so far:
1. Several handlers are executing on several threads.
2. Handlers run independently of each other. There is no synchronization needed between threads for data/race conditions.
3. Get can be called on anyone handler. When called the handler should stop calculating and let another thread call handler::get().
This really seems more like a multi-threading / concurrency question then a boost::asio question. At the moment I do not see a need to use an io_service. It seems like several threads could just be started without an io_service and some synchronization could be used between the threads.
The thread calling Handler::get() needs to wait until the io_service thread running operator() completes its calculation before it can return.
Consider using a condition variable. The handler::get() method can wait until the condition is met (i.e. operator() finishes its calculation). The io_service thread that runs operator() would notify the main thread through the condition variable.
An example of one thread notifying another thread via a condition variable is here.

Timer Queues, immediately terminate a timer?

I'm trying to achieve high frame-per-second on Windows GDI by using Windows Timer Queues. The relevant APIs are CreateTimerQueue, DeleteTimerQueueEx, CreateTimerQueueTimer, and DeleteTimerQueueTimer .
The timer is created using CreateTimerQueueTimer(&m_timer, m_timer_queue, TimerCallback, this, 0, 20, WT_EXECUTEINTIMERTHREAD); to achieve some 50fps of speed. GDI operations (some painting in the backstore, plus InvalidateRect) cannot be asynchronous, therefore I can't choose other flags but WT_EXECUTEINTIMERTHREAD so that no extra sync op is required on the drawing code. The idea is to achieve 50fps when possible, and when it's not, just show each frame at the maximum possible speed.
At the end of the animation (reached a total frame count), DeleteTimerQueueTimer is called to destroy the timer.
The problem is that DeleteTimerQueueTimer doesn't immediately turn off the callings of the callback function. When it's not possible to achieve the 50fps requirement, the timer pumps the call into a queue. Calling DeleteTimerQueueTimer inside the callback function doesn't destroy the queue. As a result, the callback is still being called even though it decided to shutdown the timer.
How do I deal with this problem?
-
On another note, the old timeSetEvent / timeKillEvent multimedia API doesn't seem to have this problem. There are no queues and the calling of the callback function is immediately stopped when I call timeKillEvent. Is it possible to achieve the same behavior with timer queues?
You can pass the WT_EXECUTEONLYONCE flag to the CreateTimerQueueTimer function. This will cause the timer to trigger only once and not periodically.
You can then reschedule the timer with the ChangeTimerQueueTimer method.
To cover the times where your drawing takes too long too complete in the frame, you can add a CriticalSection to the beginning of the TimerHandler method, which will cause the 2nd timer to wait until the first one completes.
If you want to run something at 50fps+, you'd probably do better to actually just have a draw loop which computes the amount of time between frames and scales the animation accordingly. Timers aren't really meant to fire so often. So (and this would probably be in your Idle handler). Like, this pseudocode (ignore lack of error handling):
static longlong last_frame;
while(1) {
longlong current_frame = QueryPerformanceCounter();
long delta = current_frame - last_frame;
// Do drawing here, scale amount to move by how much time has elapsed
last_frame = current_frame;
}
DeleteTimerQueueTimer will cancel the timer provided it has not already been scheduled. (When you use WT_EXECUTEINTIMERTHREAD I believe they are queued as an APC on a thread from a thread pool shared by the timer queues and worker threads. ) If it has already been scheduled (not just running) - it will be run and the DeleteTimerQueueTimer call will block until completion.
If I understand your problem correctly, may I suggest the following?
1. Before calling DeleteTimerQueueTimer - set a flag say abortAllTimers to true.
2. In each timer call back function check to see if abortAllTimers is true. If it is true - then return at once without doing any drawing.
And finally - DeleteTimerQueueTimer should not be called from the timer callback. Instead I would suggest you should call it from any other thread - say the thread you used to start the timers.
Hope this helps.

How to Use Timers in Windows

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

Resources