Regular callback scheduling - windows

I am looking for a way to schedule a callback function at a regular frequency (say 1hz) within the NT kernel. Is there any framework support for that? I read in one of the posts that a timer object can be used for that, but I did not find any example or any documentation for this use case. Any help would be appreciated.

You are looking for the SetTimer function in the Windows API. It allows you to pass a callback function pointer.
Note that you must have a working Windows message pump for this function to work - the callback occurs as part of the message processing. The OS doesn't just interrupt your program and jump to the callback function.

Related

Call API at Exit?

I'm using an API that has a 'bind' function that I call at the start of my program, but to be a good API user, I need to call the 'unbind' function when my program quits for any reason. Is there a way to do that? I can't find anything on Google, and defer api.Unbind() doesn't seem to get called. Thx.
There is no single way to get a 100% guarantee that some code is called before abnormal program termination. The closest you can get is to react to os.Interrupt (and also syscall.SIGTERM on Unix systems) and make sure your cleanup is done thereafter. A good way to achieve this is to use NotifyContext because it ties in nicely with the context package the main use of which is to allow for implementing cancellation of (potentially) long-running code.

What are events in lua functions

I get the idea of parameters in functions, but I don't know what an event is. I have also heard of JavaScript function events but since I have no js experience, I don't know what they are.
There is nothing special in Lua that can be called 'event'. I guess you are talking about general events (from Wikipedia):
In computing an event is an action that is usually initiated outside the scope of a program and that is handled by a piece of code inside the program
An example of events are a mouse click, key press, download finished, anything you can imagine.
In order to react to an event, you need to write a so-called handler, sometimes also called listener or callback, which is a piece of code that you register to react to a certain event. The available events, handling process and handler registration are all dictated by the library/framework you are using, i.e. it's not Lua specific, but Lua does provide functions as way to write handlers.
For example, in Corona SDK (overview of events/listeners), you can handle the 'touch' event as follows:
Runtime:addEventListener("touch", function(event)
print("A touch event is being handled")
...
end)
There is no such thing as an 'event' in a standard Lua function. Perhaps there is some library that provides you with them, or you could script your way around to emulate the wanted behaviour.
You can get more concrete answers if you provide info about what you want to accomplish, and show some code.

triggering kevent by force

I'm using kqueue for socket synchronization in OS X. I can register an event of interest like the following:
struct kevent change;
EV_SET(&change, connected_socket, EVFILT_READ, EV_ADD, 0, NULL, NULL);
kevent(k_queue_, &change, 1, NULL, 0, NULL);
And the question is, is there a way to trigger this event by force so that the waiting kevent call would return?
Some possibilities aside from natural writing of data to the other side of the socket :)
shutdown(2) the read side of that socket - you'll get EV_EOF in flags (silly),
Use the timeout argument and call the same handling function,
Use the self-pipe trick when you need to break the wait.
My question though: why do you need this?
Edit:
If I understand your comments correctly you are looking for a way to get around edge-triggered behavior (EV_CLEAR) for write events. I believe that the proper way of doing this is to un-register your socket from EVFILT_WRITE when you don't have anything in the outgoing queue, then re-register it again when there's data to send. It's a bit more work, but that's how it works, and you don't need any additional system calls since kevent(2) accepts both changes and results. Take a look into libevent and see how it handles this sort of stuff. And you are using non-blocking sockets, right?
I would recommend a slightly different solution.
Add another registered event to the kqueue. Specifically a EVFILT_USER.
You can use this to trigger whatever behavior you want to wake the kevent() thread up for without the code looking weird or being hard to maintain.
The OSX sources have a real rough test for it in
http://www.opensource.apple.com/source/xnu/xnu-1699.24.23/tools/tests/xnu_quick_test/kqueue_tests.c
OSX 10.6 and FreeBSD 8.1 add support for EVFILT_USER, which we can use to wake up the event loop from another thread.
Note that if you use this to implement your own condition and timedwait, you still need locks in order to avoid race conditions, as explained in this excellent answer.
See my other answer for a full code example: https://stackoverflow.com/a/31174803/432

Easiest way to read/write a file asynchronously?

I am looking for a simple way to read/write a file asynchronously using Win API. What I had is mind is something like the asynchronous winsock API (WSAxxx) completion routines. However the file API doesn't seem to have those. Are they hidden somewhere?
Waiting on the overlapped events in a seperate thread adds thread management overhead, not to mention there either needs to be a thread-per-file, or the 64 objects problem needs to be faced. Completion ports is an overkill. Reading the file synchronously on a seperate thread is irrelevant.
Any suggestions?
CreateFile and ReadFile/WriteFile functions support so-called 'overlapped' mode which is what you need. There' also ReadFileEx/WriteFileEx that work in async mode only.
In short, you need to open file with FILE_FLAG_OVERLAPPED flag and pass OVERLAPPED structure (and callback in case of xxxEx operations) to file access functions.
Here's a sample class for using it.
I know that in .net it's possible. What I don't know is to which win32 functions it maps
As soon as you step into the async territory you should forget the word "easiest"
Seriously, the easiest would be to use .NET's System.IO.FileStream with isAsync=true in constructor and BeginRead/EndRead methods.

How to deal with a second event-loop with message-dispatch?

I am working on a program which is essentially single-threaded, and its only thread is the main event-loop thread. Consequently, all its data structures are basically not protected by anything like critical region.
Things work fine until it recently integrates some new functions based on DirectShow API. Some DirectShow APIs open a second event-loop and within that second loop it dispatch messages (i.e. invoke other event-handling callbacks unpredictably). So when a second event-handling function is invoked, it might damage the data struct which is being accessed by the function that invokes the DirectShow API.
I have some experience in kernel programming. And what comes in my mind is that, for a single-threaded program, how it should deal with its data structure is very like how kernel should deal with per-CPU data structure. And in kernel, when a function accesses per-CPU data, it must disable the interrupt (very like the message-dispatching in a second event-loop). However, I find there is no easy way to either avoid invoke DirectShow API or to prevent the create of a second event-loop within them, is there any way?
mutexes. semaphores. locking. whatever name you want to call it, that's what you need.
There are several possible solutions that come to mind, depending on exactly what's going wrong and your code:
Make sure your data structures are in a consistent state before calling any APIs that run a modal loop.
If that's not possible, you can use a simple boolean variable to protect the structure. If it's set, then simply abort any attempt to update it or queue the update for later. Another option is to abort the previous operation.
If the problem is user generated events, then disable the problematic menus or buttons while the operation is in progress. Alternatively, you could display a modal dialog.

Resources