Event loop in C++ on Windows with timer queue - c++

I am writing a windows DLL in C++ and I need some sort of event loop.
Several events are periodically checked and the DLL then triggers callbacks in the client application. The polling period might differ for different events.
I wonder what is the best way to code this. The timing precision must be good but performance is the main priority.
Is it better to have several (4-5) timers in one Windows timer queue with various periods or one single timer with the smallest period? Or should I prefer a completely different solution?
Thanks

What sort of performance is the main priority? Repeatable, accurate timing is err... 'highly difficult' on a general-purpose OS like Windows because of the numerous driver interrupts. There are various timer mechanisms that can generate very accurate timeouts but not reliably. How much jitter can you tolerate? In what sort of range are your intervals? Do the callbacks have to be in any particular thread context, or could anything fire the events?
Rgds,
Martin

To directly answer the question you can set up a timer with SetTimer which takes a nIDEvent which is usually registered to a window handle. That window will then receive WM_TIMER messages with the registered identifier as wParam. You should destroy the timer when you're done with it with KillTimer. WM_TIMER has a granularity of around 10-15ms on Windows NT systems.
As said by the other posters, you would probably be better off with a truly event based system. Perhaps you could edit your post with the usecase and better answers could be suggested.

Related

Event-driven programming: callback vs message polling

I've been looking into OpenGL programming as a C++ programmer, and have seen two primary ways of dealing with event-driven programming: message polling or callback functions.
I see that the native Win32API uses a callback function, which is triggered by the DispatchMessage function.
SDL (based on the tutorials) also use some sort of callback or callback-like programming.
GLFW also uses callbacks.
SFML lets the programmer poll for individual messages anywhere in the code, usually in a loop, forming the message loop.
The X Window system, based on what I have seen, also uses message polling.
Clearly, since event systems exist in prominent environments, each must have an advantage. I was hoping someone could tell me the advantages and disadvantages of each. I am thinking of writing some programs which would heavily depend on event-driven programming, and would like to make the best decision on which path to take.
This isn't going to be complete, but here's a few things that come to mind...
I've only ever used GL for 3D, and haven't really done much in the way of GUIs. Polling for events is pretty common. More precisely, polling in a main rendering loop which processes all events in a queue and then moves on to rendering. This is because you re-render everything from scratch each frame after collecting all events and using them to update the scene's 3D state. Since a screen can only display images at a limited frame rate, it's also common to sleep during polling as any state updates won't get shown till later even if their events are triggered sooner.
If you were to process events exactly as they happen, such as part-way through drawing, then you have race conditions. Dealing with this may be an unnecessary hastle.
If you have anything animating then you already have a loop and polling is a trivial cost in contrast.
If your events are very infrequent, then you don't need to re-draw often so having a thread active and polling is a little in-efficient.
It'll be quite bad if events pile up and you're re-drawing for each one. You might find you're re-drawing more often than using a loop to process all events and render once.
I think the main issue with polling is for inactive windows that aren't in focus. Lets say you minimize your GL app. You know it won't receive any events so polling is useless. So is drawing for that matter.
Another issue is response latency. This is quite important for something like capturing mouse movement in a game. As long as you poll for events in the right order (input→update→display) this is generally OK. However, vsync can mess with the timing by delaying frames from being displayed.
I'm currently creating light weight GUI libraries for linux based on opengl and evdev.
A first one, developped in C leads me to implement message architecture, inspired by pipe usage for multithreaded communication.
For a second one, in c++, I only use callbacks, but evdev stack in linux is message driven.
My conclusion is that for peripherics (ex: mouse) which could trigger interrupts more rapidly than program could respond to, you need a fifo layer, (usualy a pipe), to make asynchronous the communication between both contexts. and thus: Messages are just asynchronous buffered callback's in multithreaded environment.
You may also use callback fifo's, to buffer your events. But organizing variables among threads is not always easy (semaphore, locking, etc). Using messages as the only interprocess syncronization mechanic helps clearing that point.

Asynchronous Agents and window messages

I'm currently playing with the Asynchronous Agents Library in Microsoft's Concurrency Runtime. I have not yet found an obvious way to signal that a task is finished by using window messages, or some other means of notifying the UI thread that the work is finished.
I know I can pass window handles and message values (WM_xxx) along to the tasks, and have the task use PostMessage() to signal the UI thread. This is somewhat ugly in my opinion, and a source of error. If an exception occurs, I have to have a catch handler that signals my UI thread. This is easily forgotten, and the exception condition might not be run very often, so it's hard to spot it.
The documentation talks about how to move data back to the UI thread. It does not make use of window messages, but polling techniques. I find it silly to set up timers to poll if a task has finished, when there are "interrupt" methods available!
It's kind of odd that this isn't built into the library, as it's not a cross platform library. It's designed to run on Windows, and Windows only, from what I understand.
Is the functionality available in the library, or do I have to hand roll this?
You can create one monitor thread with sole function of monitoring an unbounded_buffer for a windows message and dispatching that message appropriately. Have your agents know about this buffer.

Is there a way to communicate data between computers without while loops? C++

I have been struggling to try and find my answer for this on google, as I dont know the exact terms I am looking to search for.
If someone were to build an msn messenger-like program, is it possible to have always-open connections and no while(true) loop? If so, could someone point me in the direction of how this is achieved?
Using boost::asio library for socket handling, i think it is possible to define callbacks upon data reception.
The one single magic word your looking for is asynchronous I/O. This can be achieved either through using asynchronous APIs (functions such as ReadThis() that return immediately and signal on success/failure -- like but not limited by boost::asio) or by deferring blocking calls to different threads. Picking either method requires careful weighing of both the underlying implementation and the scale of your operations.
You want to use ACE. It has a Reactor pattern which will notify you when data is available to be use.
Reactor Pattern
You could have:
while(1) {
sleep(100); // 100 ms
// check if there is a message
// process message
//...
}
This is ok, but there is an overhead on servers running 10000s of threads since threads come out of sleep and check for a message, causing context-switching. Instead, operating systems provide functions like select and epoll on Linux, which allow a thread to wait on an event.
while(1) {
// wait for message
// process message
//...
}
Using wait, the thread is not "woken up" unless a message is received.
You can only hide your while loop (or some kind of loop) somewhere buried in some library or restart the waiting for next IO in an event callback, but you aren't going to be able to completely avoid it.
That's a great question. Like nj said, you want to use asynchronous I/O. Too many programs use a polling strategy. It is not uncommon to have 1000 threads running on a system. If all of them were polling, you would have a slow system. Use asynchronous I/O whenever possible.
what about udp protocol communication ? you dont have to wait in while loop for every clients
just open one connection on specified port and call receive method

How to implement a timer with interruption in C++?

I'm using the GCC compiler and C++ and I want to make a timer that triggers an interruption when the countdown is 0.
Any Ideas? Thanks in advance.
EDIT
Thanks to Adam, I know how to do it.
Now. What about multiple timers running in parallel?
Actually, these timers are for something very basic. In NCURSES, I have a list of things. When I press a key, one of the things will change colors for 5 seconds. If I press another key, another thing in the list will do the same. It's like emphasize strings depending on the user input. Is there a simpler way to do that?
An easy, portable way to implement an interrupt timer is using Boost.ASIO. Specifically, the boost::asio::deadline_timer class allows you to specify a time duration and an interrupt handler which will be executed asynchronously when the timer runs out.
See here for a quick tutorial and demonstration.
One way to do it is to use the alarm(2) system call to send a SIGALRM to your process when the timer runs out:
void sigalrm_handler(int sig)
{
// This gets called when the timer runs out. Try not to do too much here;
// the recommended practice is to set a flag (of type sig_atomic_t), and have
// code elsewhere check that flag (e.g. in the main loop of your program)
}
...
signal(SIGALRM, &sigalrm_handler); // set a signal handler
alarm(10); // set an alarm for 10 seconds from now
Take careful note of the cautions in the man page of alarm:
alarm() and setitimer() share the same timer; calls to one will interfere with use of the other.
sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.
Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time.

Processing messages is too slow, resulting in a jerky, unresponsive UI - how can I use multiple threads to alleviate this?

I'm having trouble keeping my app responsive to user actions. Therefore, I'd like to split message processing between multiple threads.
Can I simply create several threads, reading from the same message queue in all of them, and letting which ever one is able process each message?
If so, how can this be accomplished?
If not, can you suggest another way of resolving this problem?
You cannot have more than one thread which interacts with the message pump or any UI elements. That way lies madness.
If there are long processing tasks which can be farmed out to worker threads, you can do it that way, but you'll have to use another thread-safe queue to manage them.
If this were later in the future, I would say use the Asynchronous Agents APIs (plug for what I'm working on) in the yet to be released Visual Studio 2010 however what I would say given todays tools is to separate the work, specifically in your message passing pump you want to do as little work as possible to identify the message and pass it along to another thread which will process the work (hopefully there isn't Thread Local information that is needed). Passing it along to another thread means inserting it into a thread safe queue of some sort either locked or lock-free and then setting an event that other threads can watch to pull items from the queue (or just pull them directly). You can look at using a 'work stealing queue' with a thread pool for efficiency.
This will accomplish getting the work off the UI thread, to have the UI thread do additional work (like painting the results of that work) you need to generate a windows message to wake up the UI thread and check for the results, an easy way to do this is to have another 'work ready' queue of work objects to execute on the UI thread. imagine an queue that looks like this: threadsafe_queue<function<void(void)> basically you can check if it to see if it is non-empty on the UI thread, and if there are work items then you can execute them inline. You'll want the work objects to be as short lived as possible and preferably not do any blocking at all.
Another technique that can help if you are still seeing jerky movement responsiveness is to either ensure that you're thread callback isn't executing longer that 16ms and that you aren't taking any locks or doing any sort of I/O on the UI thread. There's a series of tools that can help identify these operations, the most freely available is the 'windows performance toolkit'.
Create the separate thread when processing the long operation i.e. keep it simple, the issue is with some code you are running that is taking too long, that's the code that should have a separate thread.