When should atexit() be used? - libc

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

Related

Using a vkFence with an std::condition_variable

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.

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.

Redirecting printf on iOS to user interface

I'm new to iOS development (and Obj-C), and I'm trying to port an existing C program to iOS.
The C program usually runs in the console, but I want to make a UI for it on the iPhone. I've already ported the C code, and when the simulator is run I can get the printf output in the console window. I want to avoid changing the original code as much as possible, so this is my plan:
The program takes some time to execute, so I think I need to run it on a seperate thread. It look likes I'll only need an NSInvocationOperation to call it's main method.
I will redirect stdout to a pipe.
On another thread, I will read from the pipe, and throw this to the UI. I'm not sure what might be the best concurrancy API to use for this.
Is this a good strategy for the iOS, or is there a better alternative for porting this? Are there any pitfalls I should look out for?
For concurrency, use the dispatch queues for quickest programming. See this guide: http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html
To print to the screen, you could do this in many different ways, but just use a UILabel if you just want get text up there right away. You can also format it nicely later.
Main pitfalls for multithreading are like on any OS - locking any data models that have simultaneous read/write. You can use #synchronize or make your dispatch queues thread safe by using dispatch barriers also noted in the linked guide above.

Why should I Minimize the use of system call in my code?

I wanted to know is there any reason to minimize use of system call in code and what is the alternate of not using system call ,one would say use API but api in turns use system call
Is it True??
Because most system calls have an inherent overhead. A system call is a means of tapping into the kernel, a controlled gateway towards obtaining some service.
When performing a system call, some actions are taken (warning, it's a simplification):
You invoke a library (wrapper) function
The function puts the arguments where they are expected. Also the function puts the number of the system call in eax
The function calls a trap (int 0x80 or whatever)
The processor is switched to kernel mode
The kernel invokes some system_call routine
The registers are saved onto the kernel stack
The arguments are checked to be valid
The action is performed
The registers are restored from the kernel stack
The processor is returned to user mode
The function (finally...) returns
And I probably forgot some of the steps. Doesn't this sound like a lot of work ? All you wanted is the bold part. The rest is overhead.
A system call requires that the system switches from User mode to Kernel mode. This makes system calls expensive.
An article to understand this better:
Understanding User and Kernel Mode - Jeff Atwood
First, if you use framework or APIs (e.g. by using wxWidgets instead of rendering the windows manually, or the GNU C library) your code is portable between different operating systems.
Second, you if you're using APIs you won't have problems if the manufacturer changes how the operating system works under the hood, as the APIs (should) be the same as before.
The only reason that cames to my mind right now is portability issues. If you use system calls, your code will only run on that Operating System. And if you need to compile the same source to another OS, you will be in trouble, the API may be completely different.

Which logging module to use under Perl's AnyEvent?

I am using the wonderful AnyEvent for creating an asynchronous TCP server (specifically, a MUD server).
In order to keep everything running smoothly and with as few blocking/synchronous pieces of code possible, I have replaced some modules I was using with their asynchronous counterpart, for example AnyEvent::Memcached and AnyEvent::Gearman. This allows the main program to be quite speedy, which is desirable. I have coded around the need for some of these calls to be synchronous.
One problem I currently have, and the focus of this question, is logging.
Before turning to AnyEvent for this server program, I was using Log::Log4perl as it allows me to fine-tune which modules or subroutines should be logged, at which level and to which log output (screen, file, etc).
The problem here is that the Log4perl actions (warn, info, etc) are currently performed synchronously but I have no requirement for that as long as the log lines eventually end up on the screen / file (and in the correct order).
Is Log::Log4perl still the right choice when using an asynchronous event handler such as AnyEvent, or should I look at a different module? If so, which is recommended?
AnyEvent::Log, which comes with AnyEvent, uses AnyEvent::IO, which appends to files asynchronously when IO::AIO is available (and synchronously when not).
What you are trying to avoid? If it's synchronous file IO (writing to log files/stdout etc.) then your problem would probably be solved with an asynchronous and/or buffering appender(s) rather than replacing all use of Log4perl in your code.
Log::Log4perl::Appender::Buffer seems like it might be a good start, but a completely async appender doesn't appear to exist anymore.