Using a vkFence with an std::condition_variable - callback

A VkFence can be waited upon or queried about its state. Is it possible to have a callback invoked by the Vulkan implementation when the fence is ready instead?
This would allow it to be used with objects such as a std::condition_variable. When the fence would be ready, the condition_variable would get notified.
Such an approach would also allow integration with libraries like Boost.Fiber, which would completely remove the need for the thread to sleep, but rather it could do useful work while waiting upon the fence.
If this is not possible in base Vulkan, is there an extension that allows it?

Vulkan doesn't work that way. Vulkan devices and queues execute independently of the CPU. Indeed, with one or two exceptions, Vulkan implementations only ever use CPU resources within the scope of a particular function call and only on the thread on which this call was made. Even debug callbacks are made within the scope of the function that caused the error.
There is no mechanism for Vulkan implementations to use CPU resources without the explicit consent of the user of the API (again, minus one or two exceptions). So no callbacks that act outside of an API call.
Vulkan does have a way to extract a native synchronization object from a VkFence, but it is surprisingly not useful in Windows. While you can get a HANDLE, it cannot be used by the Win32 API for waiting on it. This is mainly for interop with other APIs (like converting it to a D3D12 sync object), not for waiting on it yourself. But the file descriptor extraction operation can get a fully functional sync object... if the implementation lets you.

Related

What is system call interface?

I am new to Operating system subject. And I am having trouble in understanding system calls interface. If you could help, I will be thankful.
thanks
I have tried to simply explain the whole process of making a system call.
The kernel provides a set of interfaces by which processes running in user-space can interact with the system. These interfaces give applications controlled access to hardware, a mechanism with which to create new processes and communicate with existing ones, and the capability to request other operating system resources. 
These APIs (Application Programming Interfaces) act as the messengers between applications and the kernel, the applications issues various requests and the kernel fulfills them (or returns an error).
System calls provide a layer between the hardware and user-space processes.
But System calls and APIs are not the same thing.
APIs basically are function definitions that specify "how to obtain a specific service".
You generally don't make system calls directly, instead you use an API.
Each system call has a corresponding Wrapping routine, that specifies the API that the application program must use to invoke that system call.
(Wrapper Routines are function definitions whose only purpose is to issue a system call).
However, an API does not have to correspond to a system call, an API can offer its services directly in User mode, without making any system calls, or a single API function can make several different system calls, more so different API functions can invoke the same system call.
An API defines a set of programming interfaces used by applications. Those interfaces can be implemented as a system call, implemented through multiple system calls, or implemented without the use of system calls at all. The same API can exist on multiple systems and provide the same interface to applications while the implementation of the API itself can differ greatly from system to system. 
From the programmer's perspective, the distinction b/w API and System call is irrelevant, to them its just another function call all he/she needs to think about is the function name, parameter type and return values. From the kernel designer's point of view the distinction obviously is very significant.
Further, when a User Mode process invokes a system call, the CPU switches to Kernel Mode and starts the execution of a Kernel Function(which happens to be a assembly language function) called the System Call Handler. This System Call Handler has a similar structure to that of other "Exception Handlers".
This System Call Handler first saves the content of the registers in the kernel mode stack.
Then based on the system call number (each system call has a number associated with it and the user mode process must pass this number as a parameter so that the requested call can be identified) the System Call Handler calls the relevant System Call Service Routine which in Linux happens to be a C function that actually goes on to implement the functionality requested by the User Process.
After that's done, registers are loaded back to their previous values and the CPU switches back to User Mode.
The same process can also be represented in a different manner.
A system call interface is a set of functions for requesting a service from the kernel on the operating system they are executed on.It provides an essential interface between the process and the operating system.
For example:
open();
Is a system call used to provide access to a file in a file system and so on.

When should atexit() be used?

The GNU page says :
Your program can arrange to run its own cleanup functions if normal termination happens. If you are writing a library for use in various application programs, then it is unreliable to insist that all applications call the library's cleanup functions explicitly before exiting. It is much more robust to make the cleanup invisible to the application, by setting up a cleanup function in the library itself using atexit or on_exit.
SDL in one of it's pages says :
You can use SDL_Quit() with atexit() to ensure that it is run when your application is shutdown, but it is not wise to do this from a library or other dynamically loaded code.
What I understood from the GNU page is that it encourages the usage of atexit() in programs.
Can someone elaborate on this, taken from the SDL page ? The meaning is not so obvious :
but it is not wise to do this from a library or other dynamically loaded code.
What are the pitfalls that are to be avoided while using atexit() ?
Are the above two quotes contradicting each other ?
No, SDL is saying don't call atexit(SDL_Quit) from within a library. GNU advise you set up atexit within your library to avoid cleanup problems, SDL is saying don't call it from a different library - due to the manner in which dynamic code gets unloaded you can't be certain of ordering (especially in multithreaded apps).
Short version: call atexit(SDL_Quit) inside your program's main. If you are using or writing a wrapper library around SDL, don't call atexit(SDL_Quit) inside that library, instead call atexit(YOURLIBRARY_Quit) inside the main function (presuming that YOURLIBRARY_Quit will handle the call to SDL_Quit.
atexit() is somehow like the dtor of c++ global/static object. One pitfall I have been seeing is, the atexit callbacks are called by exit() but the while the calling thread is running the callback other threads are also running so you need to make sure you don't have concurrency issue. Like in the dtor(of global/static obj), if you destroy something, other threads may still be using it so it might cause unexpected behavior.
But this is for Linux; not familiar with windows

Why a form is needed for a SetWinEventHook callback?

Currently, I'm using the powerful SetWinEventHook() function to catch some user-interface's actions like minimizing and maximizing from other window runned by programs on the computer.
So I inspired myself by using the code provided by BrendanMcK on this post and it does work (I mean: the callback function is called when an event occurs) until the line
MessageBox.Show("Something")
is present. But I don't want to use any form or window for this program..
After some research, I figured out this kind of hook needs a message loop to allow the redirection of messages from other window handles. Apparently, calling the thread using Application.Run() should do the trick, but I would prefer something cleaner, in the C# object itself.
So my question is: is it possible to create a message loop inside an object's method?
http://bytes.com/topic/c-sharp/answers/557342-thread-message-loop-c
No, the function doesn't require a window handle so no "form" is needed. But the MSDN docs for the function is quite explicit:
The client thread that calls SetWinEventHook must have a message loop in order to receive events.
A message loop is universal in any program that want to receive notifications that are generated externally by other processes or threads. It is the common solution to the producer-consumer problem. Clearly any GUI app has a need for such a solution, Windows messages are generated by the operating system. It isn't different for SetWinEventHook(), the accessibility events originate in other programs. There is no clean mechanism to "interrupt" a thread and make it run other code, the re-entrancy problems that causes are extremely difficult to deal with. The thread has to co-operate, it must be idle and ready to receive a notification to safely process it. A message loop solves that problem.
Pumping a message loop (calling Application.Run) in a method is certainly possible. But do keep in mind that the method won't return until you explicitly stop the loop with Application.ExitThread. There is therefore usually only one good place for that call, the Main() method of your program.
Starting your project with a Winforms or WPF project template is a very good way to get this right. You have no need to actually create a window, call Application.Run() without an argument, after pinvoking SetWinEventHook.

Why use the Bundle when you can just use the Application?

I'm reading this article on how to : correctly retain variable state in Android and I'm reminded that I've never gotten a good answer (and can't find one here) for why it's better to tussle with the Bundle (which isn't a HUGE hassle, but definitely has its limitations) rather than just always have an Application overridden in your App, and just store all your persistent data members there. Is there some leakage risk? Is there a way that the memory can be released unexpectedly? I'm just not clear on this... it SEEMS like it's a totally reliable "attic" to all the Activities, and is the perfect place to store anything that you're worried might be reset when the user turns the device or suspends the app.
Am I wrong on this? Would love to get some clarity on what the true life cycle of the memory is in the Application.
Based on the answers below, let me extend my question.
Suppose I have an app that behaves differently based on an XML file that it loads at startup.
Specifically, the app is a user-info gathering app, and depending on the XML settings it will follow an open ended variety of paths (collecting info A, but not J, and offering Survey P, followed by an optional PhotoTaking opportunity etc.)
Ideally I don't have to store the details of this behavior path in a Bundle (god forbid) or a database (also ugly, but less so). I would load the XML, process it, and have the Application hold onto that structure, so I can refer to it for what to do next and how. If the app is paused and the Application is released, it's not *THAT big a hassle to check for null in my CustomFlow object (that is generated as per the XML) and re-instantiate it. It doesn't sound like this would happen all that often, anyway. Would this be a good example of where Application is the *best tool?
The question as to which method is better largely depends upon what information you are storing and need access to and who (which components, packages, etc.) needs access to that information. Additionally, settings like launchMode and configChanges which alter the lifecycle can help you to determine which method is best for you.
First, let me note, that I am a huge advocate for extending the Application object and often extend the Application class, but take everything stated here in its context as it is important to understand that there are circumstances where it simply is not beneficial.
On the Lifecycle of an Application: Chubbard mostly correctly stated that the Application has the same life as a Singleton component. While they are very close, there are some minute differences. The Application itself is TREATED as a Singleton by the OS and is alive for as long as ANY component is alive, including an AppWidget (which may exist in another app) or ContentResolver.
All of your components ultimately access the same object even if they are in multiple Tasks or Processes. However, this is not guaranteed to remain this way forever (as the Application is not ACTUALLY a Singleton), and is only guaranteed in the Google Android, rather than the manufacturer overridden releases. This means that certain things should be handled with care within the Application Object.
Your Application object will not die unless all of your components are killed as well. However, Android has the option to kill any number of components. What this means is that you are never guaranteed to have an Application object, but if any of your components are alive, there IS an Application to associate it to.
Another nice thing about Application is that it is not extricably bound to the components that are running. Your components are bound to it, though, making it extremely useful.
Things to Avoid in Application Object:
As per ususal, avoid static Contexts. In fact, often, you shouldn't store a Context in here at all, because the Application is a Context itself.
Most methods in here should be static, because you are not guaranteed to get the same Application object, even though its extremely likely.
If you override Application, the type of you data and methods store here will help you further determine whether you need to make a Singleton component or not.
Drawables and its derivatives are the most likely to "leak" if not taken care of, so it is also recommended that you avoid references to Drawables here as well.
Runtime State of any single component. This is because, again, you are not guaranteed to get back the same Application object. Additionally, none of the lifecycle events that occur in an Activity are available here.
Things to store in the Application (over Bundle)
The Application is an awesome place to store data and methods that must be shared between components, especially if you have multiple entry points (multiple components that can be started and run aside from a launch activity). In all of my Applications, for instance, I place my DEBUG tags and Log code.
If you have a ContentProvider or BroadcastReceiver, this makes Application even more ideal because these have small lifecycles that are not "renewable" like the Activity or AppWidgetProvider and can now access those data or methods.
Preferences are used to determine, typically, run options over multiple runs, so this can be a great place to handle your SharedPreferences, for instance, with one access rather than one per component. In fact, anything that "persists" across multiple runs is great to access here.
Finally, one major overlooked advantage is that you can store and organize your Constants here without having to load another class or object, because your Application is always running if one of your components is. This is especially useful for Intent Actions and Exception Messages and other similar types of constants.
Things to store in Bundle rather than Application
Run-time state that is dependent upon the presence or state of a single component or single component run. Additionally, anything that is dependant upon the display state, orientation, or similar Android Services is not preferrable here. This is because Application is never notified of these changes. Finally, anything that depends upon notification from that Android System should not be placed here, such as reaction to Lifecycle events.
And.... Elsewhere
In regard to other data that needs to be persisted, you always have databases, network servers, and the File System. Use them as you always would have.
As useful and overlooked as the Application is, a good understanding is important as it is not ideal. Hopefully, these clarifications will give you a little understanding as to why gurus encourage one way over the other. Understand that many developers have similar needs and most instruction is based on what techniques and knowledge a majority of the community has. Nothing that Google says applies to all programmer's needs and there is a reason that the Application was not declared Final.
Remember, there is a reason Android needs to be able to kill your components. And the primary reason is memory, not processing. By utilizing the Application as described above and developing the appropriate methods to persist the appropriate information, you can build stronger apps that are considerate to the System, the User, its sibling components AND other developers. Utilizing the information that everyone here has provided should give you some great guidance as to how and when to extend your Application.
Hope this helps,
FuzzicalLogic
I prefer to subclass Application and point my manifest to that. I think that's the sane way of coding android although the Android architects from Google think you should use Singletons (eek) to do that. Singletons have the same lifetime as Application so everything that applies to them applies to Application except much less dependency mess Singletons create. Essentially they don't even use bundles. I think using subclass Application has dramatically made programming in Android much faster with far less hassle.
Now for the downside. Your application can be shutdown should the phone need more memory or your Application goes into the background. That could mean the user answered the phone or checked their email. So for example, say you have an Activity that forces the user to login to get a token that other Activities will use to make server calls. That's something you might store in your service object (not android service just a class that sends network calls to your server) that you store in your subclass of Application. Well if your Application gets shutdown you'll loose that token, and when the user clicks the back button your user might return to an Activity that assumes you are already authenticated and boom your service class fails to work.
So what can you do? Continue to use Bundle awfulness? Well no you could easily store security tokens into the bundle (although there might be some security issues with that depending on how this works for your app), or you have to code your Activities to not assume a specific state the Application is in. I had to check for a loss of the token and redirect the user back to the login screen when that happens. But, depending on how much state your Application object holds this could be tricky. But keep in mind your Application can know when it's being shutdown and persist it's internal state to a bundle. That at least allows you to keep your Objects in memory for 99% of the time your Application, and only save/restore when it gets shutdown rather than constantly serializing and deserializing with boiler plate code whenever you move between Activities. Using Application lets you centralize how your program can be brought up and shutdown, and since it normally lives longer than any one activity it can reduce the need for the program to reconstitute the guts of your App as the user moves between Activities. That makes your code cleaner by keeping out details of the app from every Activity, reduces overhead if your Application is already built, shares common instances/code, and allows Activities to be reclaimed without loosing your program all together. All good programs need a centralized hub that is the core, and subclassing Application gives you that while allowing you to participate in the Android lifecycle.
My personal favorite is to use http://flexjson.sourceforge.net/ to serialize my Java objects into bundles as JSON if I need to send objects around or save them. Far easier than writing to sqlite DB when all you need to do is persist data. And nice when sending data between two Activities using objects instead of broken apart primitives.
Remember by centralizing your model in the Application you create a place to share code between multiple Activities so you can always delegate an Activities persistence to an object in the Application by hooking the onPause() as well allowing persistence to be centrally located.
The short answer is: use bundles as it makes saving your state out when you're backgrounded easier. Also, it's complicated.
The long answer:
My understanding is, as soon as you Activity's onPause method is called (and onSaveInstanceState which gives you a bundle into which you should store your Activity's data) your process can be terminated without further warning. Later, when the user comes back to your application, your activity is given an onCreate call with that original bundle from which to restore its state. This will happen to all your activitys in what was your original stack.
Being able to restore your state from the bundle (which Android will save for you as your process goes away) is how Android maintain's the myth of multi-tasking. If you don't dump your activity's state out to a bundle each time onSaveInstanceState is called, your app will look like it's been restarted when the user may have just switched out for a second. This can be especially troubling when the system is resource constrained as the system would need to kill off processes more often in order to keep the device running quickly
Why the Application can be Bad
The Application does not actually get a chance to save any of its data if the process is shut down. It does have an onDestroy method but the docs will tell you that this actually never gets called by the system on an actual device. This means that, in the constrained case I mentioned above, any incidental information about what's going on within an Activity (if you've saved it in the Application) will be lost if the process is ended.
Developer's often miss this case (and it can be really annoying for users) because they're either running on a dev phone which never gets hit with using many applications at the same time. We're also never using the app for a while, then switching to another application and, after a while, switching back again.

Using PLCrashReporter, can you receive events before the crash?

We want to do additional processing (i.e. log the current state) once PLCrashReporter has detected an error (either an exception, signal, etc.) but before the app terminates. Does anyone know if this is possible using PLCrashReporter?
To expand on Andreas' answer --
I've implemented development support in trunk for -[PLCrashReporter setCrashCallbacks:], which permits the execution of a function post-crash, prior to the program exiting.
This wasn't originally included due to the difficulty of implementing async-safe code that can be executed in the context of a crashed process -- it's difficult enough to do that I didn't think anyone would want to do it.
To quote the documentation I wrote for the feature in PLCrashReporter trunk (I don't have a rendered copy posted yet, since the feature has not yet been released):
Async-Safe Programming Guide
Plausible CrashReporter provides support for executing an application specified function in the context of the crash reporter's signal handler, after the crash report has been written to disk. This was a regularly requested feature, and provides the ability to implement application finalization in the event of a crash. However, writing code intended for execution inside of a signal handler is exceptionally difficult, and is not recommended.
Program Flow and Signal Handlers
When the signal handler is called the normal flow of the program is interrupted, and your program is an unknown
state. Locks may be held, the heap may be corrupt (or in the process of being updated), and your signal
handler may invoke a function that was being executed at the time of the signal. This may result in deadlocks,
data corruption, and program termination.
Async-Safe Functions
A subset of functions are defined to be async-safe by the OS, and are safely callable from within a signal handler. If
you do implement a custom post-crash handler, it must be async-safe. A table of POSIX-defined async-safe functions
and additional information is available from the CERT programming guide - SIG30-C.
Most notably, the Objective-C runtime itself is not async-safe, and Objective-C may not be used within a signal
handler.
No, this is not possible. You would have to do your own logging and store that on the filesystem. On the next startup, you could send it alongside the crash report to your server. E.g. using QuincyKit which uses PLCrashReporter and then your own server or HockeyApp.net.
Note: I am the developer of QuincyKit and co-developer of HockeyApp.