Timers in vxWorks 6.9 - c++

In vxWorks 6.9 you can create timers, which are really just wrappers for a watchdog. You supply these guys a function pointer, a delay, and up to one parameter, and after the delay the function is called with the parameter. However, it is called in the interrupt context. This (for some reason) means you cannot call any "blocking" functions or the system literally crashes. You cannot call printf and you cannot call upon an object's public function, ie you cannot do this:
void Foo::WdCallback(Foo *foo){
foo->DoThing();
}
wdStart(wd, 16, (FUNCPTR)Foo::WdCallback, (_Vx_usr_arg_t)my_foo_ptr);
as it will also crash for reasons I don't understand.
What other way can we create a timer/timeout in vxWorks so that we can actually do something useful with the callback? One method I have seen is using a message queue - the watchdog function will call upon a message queue send function. However this means that a task must be created to dequeue that message queue somewhere else. I've also read that the watchdog callback could give a semaphore allowing a task to continue, but that means we have to create a task for every single timer-based function we want..
It looks like no matter what road we take with watchdogs, or timers, in vxWorks, we have to create an entire task just to be able to handle the watchdog callback due to the interupt context. There has to be a less ridiculous way to do this. Is there a purely C++ way to write a timer? Or a simpler vxWorks implementation?

C++ shall not be used for function being executed in an interrupt context. The watchdog here is executed in the context of the system tick interrupt.
If you want to keep C++ code, make sure that no new/delete operation will be performed and you would need to compile the code with addition flags (this should be documented in the VxWorks Programmer's Guide at the C++ section => -fno-rtti -fno-exceptions).

Related

ACE C++ - How do I implement timeout for a function call?

I need to wrap a function in a timeout, using ACE in C++.
This function is waiting for a response from the OS, and sometimes it does not return.
I cannot modify the function, so I cannot put the abort condition into it directly. I have to add a timeout to the function externally.
I saw a similar question for it in boost -
C++: How to implement a timeout for an arbitrary function call?
however, I am using ACE.
Put the function in a separate thread. If the thread hasn't exited within the timeout, then detach it and let it run to finish in the background without getting any result from it.
Note that this won't work if the function has side-effects (like writing to a file).

How to control (i.e. abort) the current evaluation of a QScriptEngine

I evaluate JavaScript in my Qt application using QScriptEngine::evaluate(QString code). Let's say I evaluate a buggy piece of JavaScript which loops forever (or takes too long to wait for the result). How can I abort such an execution?
I want to control an evaluation via two buttons Run and Abort in a GUI. (But only one execution is allowed at a time.)
I thought of running the script via QtConcurrent::run, keeping the QFuture and calling cancel() when the Abort is was pressed. But the documentation says that I can't abort such executions. It seems like QFuture only cancels after the current item in the job has been processed, i.e. when reducing or filtering a collection. But for QtConcurrent::run this means that I can't use the future to abort its execution.
The other possibility I came up with was using a QThread and calling quit(), but there I have a similar problems: It only cancels the thread if / as soon as it is waiting in an event loop. But since my execution is a single function call, this is no option either.
QThread also has terminate(), but the documentation makes me worry a bit. Although my code itself doesn't involve mutexes, maybe QScriptEngine::evaluate does behind the scenes?
Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.
Is there another option I am missing, maybe some asynchronous evaluation feature?
http://doc.qt.io/qt-4.8/qscriptengine.html#details
It has a few sections that address your concerns:
http://doc.qt.io/qt-4.8/qscriptengine.html#long-running-scripts
http://doc.qt.io/qt-4.8/qscriptengine.html#script-exceptions
http://doc.qt.io/qt-4.8/qscriptengine.html#abortEvaluation
http://doc.qt.io/qt-4.8/qscriptengine.html#setProcessEventsInterval
Hope that helps.
While the concurrent task itself can't be aborted "from outside", the QScriptEngine can be told (of course from another thread, like your GUI thread) to abort the execution:
QScriptEngine::abortEvaluation(const QScriptValue & result = QScriptValue())
The optional parameter is used as the "pseudo result" which is passed to the caller of evaluate().
You should either set a flag somewhere or use a special result value in abortEvaluation() to make it possible for the caller routine to detect that the execution was aborted.
Note: Using isEvaluating() you can see if an evaluation is currently running.

One-Shot Timer in C++ on WinCE

I'm writing an event handling function, f(d), which receives some data, d, and must take take an action X(d), then sleep for 100ms, then take another action Y(d). I would implement it as:
void f(d)
{
X(d);
Sleep(100);
Y(d);
}
However, f(d) is called from a single-threaded event handler, so the Sleep(100) is unacceptable.
I would like to do the following:
void f(d)
{
X(d);
ScheduleOneShotTimer(Y,d,100);
}
I could implement ScheduleOneShotTimer by creating a new thread for each call, passing the data as the thread parameter, and calling Sleep before executing Y(d). However, as this event may occur up to 100 times per second, I'm concerned about the overhead involved with creating a destroying all those threads.
Preferably there would be operating system level support for a "one-shot timer", but I don't think this is the case on CE. I know about SetTimer, but that is not applicable to me because I am writing a "Console Application" that has no message loop.
Any other suggestions for how to structure this would be appreciated.
Call the timeSetEvent API (a completely non-intuitive API name, I know). Use a callback function and the TIME_ONESHOT parameter.
I'd create one thread that would keep a queue of timestamp-callback pairs, sleep for 100ms (or something smaller) and then execute all elapsed callbacks.
OFC with all inter-thread synchronization (interlocking on a critical section, etc).
It's a performance-conscious solution, not a precision-oriented one. As callbacks pile up, it may take longer than exactly 100ms to execute. But since you're measuring time with Wait (which is not precise) I guess it may be good enough.

Avoid stuck calling callback

This is a question about generic c++ event driven applications design.
Lets assume that we have two threads, a "Dispatcher" (or "Engine"...) and a "Listener" (or "Client"...).
Let's assume that I write the Dispatcher code, and release it as a library. I also write the Listener interface, of course.
When the Dispatcher executes (after Listener registration)
listenerInstance.onSomeEvent();
the event handling code will actually be executed by the Dispatcher thread, so if the person that implements the Listener writes something like
void Listener::onSomeEvent() { while(true) ; }
The Dispatcher will stuck forever.
Is there a "plain old c++" (I mean no boost or libsigc++) way to "decouple" the two classes, so I can be sure that my Dispatcher will work fine whatever the Listeners does in the callbacks?
bye and thanks in advance,
Andrea
Well if the event gets invoked in the same thread (as I seem to understand can be a requirement), then there isn't much you can do about it.
If this is under a Win32 app with a message pump, you could register a windows message and call PostMessage with data representing this event and you can patch the message loop to interpret that message and call the event. What you gain is a decoupling of sorts, the event call is asynchronous (ie the event call will return no matter what). But later on when you process your messages and actually call the event, your main thread will still be stalled and nothing else will run until the event handler is ready.
Another alternative is just creating a new thread (or using a thread pool) for your call. This won't work for events that require a certain thread (ie ui updating threads). Additionally this adds synchronization overhead and thread spawning overhead AND you might starve the system of threads and/or cpu time.
But really, I don't think it's your job as the library designer to anticipate and avoid these problems. If the end-user wants to create a long event handler, let him spawn a new thread on his own. If he doesn't and just wants his specific thread to handle an event, let him. It simplifies your job and doesn't add any overhead that's not needed.
I'm afraid there's no native C++ way to do this. For windows, you can use asynchronous procedure calls (APC)
One approach could be to call the onSomeEvent into a dedicated thread. This is not 100% bullet proof but it would avoid the while(true); issue.
I hope it helps
There is a pure C++ way to achieve what you're mentioning. However, it's very ineffective. Here's a sample:
class Listener
{
bool myHasEvent;
private:
void ProcessEvent()
{
while (true)
{
if (!myHasEvent)
continue; //spin lock
// Do real processing
myHasEvent = false;
}
}
public:
void onSomeEvent() { myHasEvent = true; }
};
However, I would recommend against this approach. Instead, I would transform this into more platform-specific code. I would replace the if (!myHasEvent) continue; spin lock with a OS-specific wait routine (i.e. WaitForSingleObject on Win32) passing an Event Handle. Then, in onSomeEvent, instead of myHasEvent = true; I would set the event into signaled state (i.e. SetEvent on Win32). This would be a lot more effective because the thread wouldn't eat processor time during waiting.
Another method is the PostMessage as suggested by Blindly.

thread-safe function pointers in C++

I'm writing a network library that a user can pass a function pointer to for execution on certain network events. In order to keep the listening loop from holding up the developer's application, I pass the event handler to a thread. Unfortunately, this creates a bit of a headache for handling things in a thread-safe manner. For instance, if the developer passes a function that makes calls to their Windows::Forms application's elements, then an InvalidOperationException will be thrown.
Are there any good strategies for handling thread safety?
Function pointers can not be thread safe as they declare a point to call. So they are just pointers.
Your code always runs in the thread it was called from (via the function pointer).
What you want to achieve is that your code runs in a specific thread (maybe the UI thread).
For this you must use some kind of queue to synchronize the invocation into the MainThread.
This is exactly what .Net's BeginInvoke()/Invoke() on a Form do. The queue is in that case (somewhere deep inside the .NET framework) the windows message queue.
But you can use any other queue as long as the "correct" thread reads and executes the call requests from that queue.