Are asynchronous Windows Runtime calls guaranteed to expire? - windows-runtime

The Windows Runtime heavily uses asynchronous patterns, offloading long(-er) running tasks to the thread pool. I've read through all articles in Threading and async programming, but couldn't find an answer to my question:
Are all Windows Runtime asynchronous calls guaranteed to return at some point?

As #Paulo mentions in the comments, this depends entirely on the how the code is written. It is easy to write your own async code that never returns, and it is trivial to deadlock your application using platform APIs by doing a .Wait() from the UI thread.
Fundamentally, an async operation is a function that returns an object (often called a "promise" or a "future") and then that object either sets an event or calls a callback function at some future point in time (this is the "logical" return value of the async operation).
Either part of this could fail -- the initial function might never get around to returning the promise object, or the promise might never get around to calling the callback / setting the event.

Related

What thread runs the callback passed to cudaStreamAddCallback?

If I register a callback via cudaStreamAddCallback(), what thread is going to run it ?
The CUDA documentation says that cudaStreamAddCallback
adds a callback to be called on the host after all currently enqueued items in the stream have completed. For each cudaStreamAddCallback call, a callback will be executed exactly once. The callback will block later work in the stream until it is finished.
but says nothing about how the callback itself is called.
Just to flesh out comments so that this question has an answer and will fall off the unanswered queue:
The short answer is that this is an internal implementation detail of the CUDA runtime and you don't need to worry about it.
The longer answer is that if you look carefully at the operation of the CUDA runtime, you will notice that context establishment on a device (be it explicit via the driver API, or implicit via the runtime API) spawns a small thread pool. It is these threads which are used to implement features of the runtime like stream command queues and call back operations. Again, an internal implementation detail which the programmer doesn't need to know about.

Signature of Error throwing Function in TypeScript

Is there a "best practice" sort of way how one would mark a function in TypeScript with the information that this function throws an error?
In Java one would annotate the function's signature with "throws XYError". This does not work with TypeScript.
I understand that it is not needed for the code to run but as far as I am concerned it is cleaner code when the function signature already tells me such information.
Any reasoned tips on how you guys deal with that situation are appreciated.
Your function should return a Promise. This is the natural way of representing the eventual completion or failure of an asynchronous operation.
This is for asynchronous functions only. And in my opinion, the best practice is to not throw exceptions from synchronous functions at all.
accessing files, databases, network services - these should be asynchronous
argument is out of range - this traditionally is not an error in javascript: pop() from empty array returns undefined, substring() with invalid range returns empty string, and this is a good thing IMO - it results in much cleaner code in the caller
argument is null - compile with --strictNullChecks on, then you can rely on callers never passing null
stack overflow, out of memory - these are not thrown explicitly, there is no point in declaring them because any function may throw them (in Java, these are runtime exceptions and are not checked too)
Is there anything else left that warrants throwing an exception from synchronous function? If it is, I think it's too rare to have an explicit support in the language.

Callback functions: what are they in computer programming languages?

I see a lot of callback functions in low-level API's like Win32. But I am confused on what a callback function or callback subroutine is. Is an event in c# considered a callback function?
A callback function is a function that is passed to something else, which will later call the function to notify the user of something. This implies that there must be a way to pass a reference to a function to another, for instance a type of function pointer. In .NET, delegates are used.
An event handler method is an example of a callback function.
In .NET a delegate is the closest match to a Win32 API type callback, though a delegate is far more functional. Events themselves are based on underlying delegates.
The most common use for a callback in the Win32 API is to enumerate resource or something similar. For example the EnumChildWindows API will kick off the enumeration of all the child windows of a specific window and call your custom callback routine for each child window found. Within that callback you can perform any actions that are relevant to your requirement that relate to the specific child window, for example you might be trying to enumerate the windows to programatically find a specific window based on some custom criteria that relates to that window, and once you find the window you can force the termination of the enumeration by returning false from the callback.
In .NET this pattern of using a callback is not required because a more formalized solution is available using the IEnumerable interface.
Callbacks are a specific case of continuations. To quote PFPL, ch 30:
[first class] continuations ... are ordinary values with an indefinite lifetime that
can be passed and returned at will in a computation. Continuations never
“expire”, and it is always sensible to reinstate a continuation without compromising safety. Thus continuations support unlimited “time travel” — we can go back to a previous point in the computation and then return to
some point in its future, at will.
Why are continuations useful? Fundamentally, they are representations
of the control state of a computation at a given point in time. Using continuations we can “checkpoint” the control state of a program, save it in a
data structure, and return to it later
Thus callbacks are just yet another example of continuations. Their use for asynchronous event processing follows from the ability to restore execution to some state via the continuation.
Continuations are particularly easy to use in languages with first class functions, and higher-order functions.
References: Practical Foundations for Programming
Languages, Robert Harper, 2011.

What is the difference between message-passing and method-invocation?

Is there a difference between message-passing and method-invocation, or can they be considered equivalent? This is probably specific to the language; many languages don't support message-passing (though all the ones I can think of support methods) and the ones that do can have entirely different implementations. Also, there are big differences in method-invocation depending on the language (C vs. Java vs Lisp vs your favorite language). I believe this is language-agnostic. What can you do with a passed-method that you can't do with an invoked-method, and vice-versa (in your favorite language)?
Using Objective-C as an example of messages and Java for methods, the major difference is that when you pass messages, the Object decides how it wants to handle that message (usually results in an instance method in the Object being called).
In Java however, method invocation is a more static thing, because you must have a reference to an Object of the type you are calling the method on, and a method with the same name and type signature must exist in that type, or the compiler will complain. What is interesting is the actual call is dynamic, although this is not obvious to the programmer.
For example, consider a class such as
class MyClass {
void doSomething() {}
}
class AnotherClass {
void someMethod() {
Object object = new Object();
object.doSomething(); // compiler checks and complains that Object contains no such method.
// However, through an explicit cast, you can calm the compiler down,
// even though your program will crash at runtime
((MyClass) object).doSomething(); // syntactically valid, yet incorrect
}
}
In Objective-C however, the compiler simply issues you a warning for passing a message to an Object that it thinks the Object may not understand, but ignoring it doesn't stop your program from executing.
While this is very powerful and flexible, it can result in hard-to-find bugs when used incorrectly because of stack corruption.
Adapted from the article here.
Also see this article for more information.
as a first approximation, the answer is: none, as long as you "behave normally"
Even though many people think there is - technically, it is usually the same: a cached lookup of a piece of code to be executed for a particular named-operation (at least for the normal case). Calling the name of the operation a "message" or a "virtual-method" does not make a difference.
BUT: the Actor language is really different: in having active objects (every object has an implicit message-queue and a worker thread - at least conceptionally), parallel processing becones easier to handle (google also "communicating sequential processes" for more).
BUT: in Smalltalk, it is possible to wrap objects to make them actor-like, without actually changing the compiler, the syntax or even recompiling.
BUT: in Smalltalk, when you try to send a message which is not understoof by the receiver (i.e. "someObject foo:arg"), a message-object is created, containing the name and the arguments, and that message-object is passed as argument to the "doesNotUnderstand" message. Thus, an object can decide itself how to deal with unimplemented message-sends (aka calls of an unimplemented method). It can - of course - push them into a queue for a worker process to sequentialize them...
Of course, this is impossible with statically typed languages (unless you make very heavy use of reflection), but is actually a VERY useful feature. Proxy objects, code load on demand, remote procedure calls, learning and self-modifying code, adapting and self-optimizing programs, corba and dcom wrappers, worker queues are all built upon that scheme. It can be misused, and lead to runtime bugs - of course.
So it it is a two-sided sword. Sharp and powerful, but dangerous in the hand of beginners...
EDIT: I am writing about language implementations here (as in Java vs. Smalltalk - not inter-process mechanisms.
IIRC, they've been formally proven to be equivalent. It doesn't take a whole lot of thinking to at least indicate that they should be. About all it takes is ignoring, for a moment, the direct equivalence of the called address with an actual spot in memory, and consider it simply as a number. From this viewpoint, the number is simply an abstract identifier that uniquely identifies a particular type of functionality you wish to invoke.
Even when you are invoking functions in the same machine, there's no real requirement that the called address directly specify the physical (or even virtual) address of the called function. For example, although almost nobody ever really uses them, Intel protected mode task gates allow a call to be made directly to the task gate itself. In this case, only the segment part of the address is treated as an actual address -- i.e., any call to a task gate segment ends up invoking the same address, regardless of the specified offset. If so desired, the processing code can examine the specified offset, and use it to decide upon an individual method to be invoked -- but the relationship between the specified offset and the address of the invoked function can be entirely arbitrary.
A member function call is simply a type of message passing that provides (or at least facilitates) an optimization under the common circumstance that the client and server of the service in question share a common address space. The 1:1 correspondence between the abstract service identifier and the address at which the provider of that service reside allows a trivial, exceptionally fast, mapping from one to the other.
At the same time, make no mistake about it: the fact that something looks like a member function call doesn't prevent it from actually executing on another machine or asynchronously, or (frequently) both. The typical mechanism to accomplish this is proxy function that translates the "virtual message" of a member function call into a "real message" that can (for example) be transmitted over a network as needed (e.g., Microsoft's DCOM, and CORBA both do this quite routinely).
They really aren't the same thing in practice. Message passing is a way to transfer data and instructions between two or more parallel processes. Method invocation is a way to call a subroutine. Erlang's concurrency is built on the former concept with its Concurrent Oriented Programing.
Message passing most likely involves a form of method invocation, but method invocation doesn't necessarily involve message passing. If it did it would be message passing. Message passing is one form of performing synchronization between to parallel processes. Method invocation generally means synchronous activities. The caller waits for the method to finish before it can continue. Message passing is a form of a coroutine. Method-invocation is a form of subroutine.
All subroutines are coroutines, but all coroutines are not subroutines.
Is there a difference between message-passing and method-invocation, or can they be considered equivalent?
They're similar. Some differences:
Messages can be passed synchronously or asynchronously (e.g. the difference between SendMessage and PostMessage in Windows)
You might send a message without knowing exactly which remote object you're sending it to
The target object might be on a remote machine or O/S.

Writing Signal handlers for Shared libraries or DLL?

I have a Application A(by some company X). This application allows me to extend the functionality by allowing me to write my own functions.
I tell the Application A to call my user functions in the Applications A's configuration file (this is how it knows that Appl A must call user written Functions). The appl A uses Function pointers which I must register with Application A prior to calling my user written functions.
If there is a bug or fault in my user written functions in production, the Appl A will stop functioning. For example, if I have a segmentation fault in my User written functions.
So Application A will load my user written function from a shared DLL file. This means that my user written functions will be running in Application A' Process address space.
I wish to handle certain signals like Segmentation fault, divide by zero and stack overflow, but applications A has its own signal handlers written for this,
How can I write my own signal handlers to catch the exceptions in my user written functions, so that I can clean up gracefully w/o affecting much of Application A? Since my user functions will be called in Applications A's process, the OS will call signal handlers written in Application A and not my user functions.
How can I change this? I want OS to call signal handlers written in my functions but only for signal raised by my functions, which is asynchronous in nature.
Note: I do not have the source code of Application A and I cannot make any changes to it, because it's controlled by a different company.
I will be using C , and only C on a Linux, solaris and probably windows platforms.
You do not specify which platform you're working with, so I'll answer for Linux, and it should be valid for Windows as well.
When you set your signal handlers, the system call that you use returns the previous handler. It does it so that you can return it once you are no longer interested in handling that signal.
Linux man page for signal
MSDN entry on signal
Since you are a shared library loaded into the application you should have no problems manipulating the signals handlers. Just make sure to override the minimum you need in order to reduce the chances of disrupting the application itself (some applications use signals for async notifications).
The cleanest way to do this would be run your application code in a separate process that communicates with the embedded shared DLL code via some IPC mechanism. You could handle whatever signals you wanted in your process without affecting the other process. Typically the conditions you mention (seg fault, divide by zero, stack overflow) indicate bugs in the program and will result in termination. There isn't much you can do to "handle" these beyond fixing the root cause of the bug.
in C++, you can catch these by putting your code in a try-catch:
try
{
// here goes your code
}
catch ( ... )
{
// handle segfaults
}