How does g_main_loop_unref(GMainLoop* loop) work? - glib

The Question
Excerpt from the documentation:
Decreases the reference count on a GMainLoop object by one.
If the result is zero, free the loop and free all associated memory.
I could not find information regarding this reference counter. What is it initially set to and how is it used?
Details
In particular, I'm confused about this piece of example code (in the main method) (note that set_cancel is a static method:
void (*old_sigint_handler)(int);
old_sigint_handler = signal (SIGINT, set_cancel);
/* Create a new glib main loop */
data.main_loop = g_main_loop_new (NULL, FALSE);
old_sigint_handler = signal (SIGINT, set_cancel);
/* Run the main loop */
g_main_loop_run (data.main_loop);
signal (SIGINT, old_sigint_handler);
g_main_loop_unref (data.main_loop);
If g_main_loop is blocking, how it ever going to stop? I could not find information on this signal method either. But that might be native to the library (although I do not know).
Note: I reduced the code above to what I thought was the essential part. It is from a camera interface library called aravis under docs/reference/aravis/html/ArvCamera.html

I could not find information regarding this reference counter. What is it initially set to and how is it used?
It is initially set to 1. Whenever you store a reference to the object you increment the reference counter, and whenever you remove a reference you decrement the reference counter. It's a form of manual garbage collection. Just google "reference counting" and you'll get lots of information.
If g_main_loop is blocking, how it ever going to stop?
Somewhere someone will call g_main_loop_quit. Judging by the question I'm guessing you're not very familiar with the concept of an event loop—GLib's manual isn't a very gentle introduction to the basic concept, you may want to try the Wikipedia article or just search for "event loop".
I could not find information on this signal method either. But that might be native to the library (although I do not know).
The signal is a standard function (both C and POSIX). Again, there is lots of information out there, including good old man pages (man 2 signal).

Related

D/Dlang: Lua interface, any way to force users to have no access to intermediate objects?

Status: Sort of solved. Switching Lua.Ref (close equivalent to LuaD LuaObject) to struct as suggested in answer has solved most issues related to freeing references, and I changed back to similar mechanism LuaD uses. More about this in the end.
In one of my project, I am working with Lua interface. I have mainly borrowed the ideas from LuaD. The mechanism in LuaD uses lua_ref & lua_unref to be able to move lua table/function references in D space, but this causes heavy problems because the calls to destructors and their order is not guaranteed. LuaD usually segfaults at least at the program exit.
Because it seems that LuaD is not maintained anymore, I decided to write my own interface for my purposes. My Lua interface class is here: https://github.com/mkoskim/games/blob/master/engine/util/lua.d
Usage examples can be found here:
https://github.com/mkoskim/games/blob/master/demo/luasketch/luademo.d
And in case you need, the Lua script used by the example is here:
https://github.com/mkoskim/games/blob/master/demo/luasketch/data/test.lua
The interface works like this:
Lua.opIndex pushes global table and index key to stack, and return Top object. For example, lua["math"] pushes _G and "math" to stack.
Further accesses go through Top object. Top.opIndex goes deeper in the table hierarchy. Other methods (call, get, set) are "final" methods, which perform an operation with the table and key at the top of the stack, and clean the stack afterwards.
Close everything works fine, except this mechanism has nasty quirk/bug that I have no idea how to solve it. If you don't call any of those "final" methods, Top will leave table and key to the stack:
lua["math"]["abs"].call(-1); // Works. Final method (call) called.
lua["math"]["abs"]; // table ref & key left to stack :(
What I know for sure, is that playing with Top() destructor does not work, as it is not called immediately when object is not referenced anymore.
NOTE: If there is some sort of operator to be called when object is accessed as rvalue, I could replace call(), set() and get() methods with operator overloads.
Questions:
Is there any way to prevent users to write such expressions (getting Top object without calling any of "final" methods)? I really don't want users to write e.g. luafunc = lua["math"]["abs"] and then later try to call it, because it won't work at all. Not without starting to play with lua_ref & lua_unref and start fighting with same issues that LuaD has.
Is there any kind of opAccess operator overloading, that is, overloading what happens when object is used as rvalue? That is, expression "a = b" -> "a.opAssign(b.opAccess)"? opCast does not work, it is called only with explicit casts.
Any other suggestions? I internally feel that I am looking solution from wrong direction. I feel that the problem reside in the realm of metaprogramming: I am trying to "scope" things at expression level, which I feel is not that suitable for classes and objects.
So far, I have tried to preserve the LuaD look'n'feel at interface user's side, but I think that if I could change the interface to something like following, I could get it working:
lua.call(["math", "abs"], 1); // call lua.math.abs(2)
lua.get(["table", "x", "y", "z"], 2); // lua table.x.y.z = 2
...
Syntactically that would ensure that reference to lua object fetched by indexing is finally used for something in the expression, and the stack would be cleaned.
UPDATE: Like said, changing Lua.Ref to struct solved problems related to dereferencing, and I am again using reference mechanism similar to LuaD. I personally feel that this mechanism suits the LuaD-style syntax I am using, too, and it can be quite a challenge to make the syntax working correctly with other mechanisms. I am still open to hear if someone has ideas to make it work.
The system I sketched to replace references (to tackle the problem with objects holding references living longer than lua sandbox) would probably need different kind of interface, something similar I sketched above.
You also have an issue when people do
auto math_abs = lua["math"]["abs"];
math_abs.call(1);
math_abs.call(3);
This will double pop.
Make Top a struct that holds the stack index of what they are referencing. That way you can use its known scoping and destruction behavior to your advantage. Make sure you handle this(this) correctly as well.
Only pop in the destructor when the value is the actual top value. You can use a bitset in LuaInterface to track which stack positions are in use and put the values in it using lua_replace if you are worried about excessive stack use.

Do i need to do g_object_unref() on glib signal parameters?

when i connect a signal to a callback function the callback functions gets passed parameters. Is the reference counter increased before the objects get passed to my callback function or do i have to increase it by myself.
I guess there must be some sort of convention for that because nothing like that is mentioned in the documentation of gtk or libgobject.
Generally, you do not assume a reference on an object when it is passed to your callback. You only assume a reference when the object is the return value of a method which is annotated with "transfer full". You can see these annotations in the documentation.
(I say "generally" because there may always be badly constructed libraries whose API violates these guidelines. You can't do a whole lot about that, though.)

pthread mutex: get state

I was looking through some code that provides a C/C++ wrapper for a pthread mutex. The code keeps a shadow variable for signaled/not signaled condition. The code also ignores return values from functions like pthread_mutex_lock and pthread_mutex_trylock, so the shadow variable may not accurately reflect the state of the mutex (ignoring the minor race condition).
Does pthread provide a way to query a mutex for its state? A quick read of the pthread API does not appear to offer one. I also don't see anything interesting that operates on pthread_mutexattr_t.
Or should one use trylock, rely upon EBUSY, and give up ownership if acquired?
Thanks in advance.
There is no such function because there would be no point. If you queried the state of a mutex without trying to acquire it, as pthread_mutex_trylock() does, then the result you get could be invalidated immediately by another thread changing that mutex's state.

How to use NIF to interact with C code that keeps state across calls (i.e., linked lists as NIF)

I wanted to create a linked-list data structure that was implemented in C. The idea was that one would create a linked list
ll:new() -> listId.
ListId, above, represents a "pointer" of some type that would get passed back to the C code which would function as some type of handle on the list. I was hoping not to have to pass the list itself back and forth since I imagined lists could get very, very large. Once the linked list was created, users would then interact with it in obvious ways:
ll:add(ListId, Elt)
ll:add_after(ListId, Pos, Elt)
I imagined I would do this via Erlang's NIF capabilities. Now, for this to work the C side has to maintain the list across multiple calls to add, add_after, etc.
In straight C, I would have a main function that a user interacts with that would keep the program alive thereby keeping the linked list persisted for the life of the user's interaction with the program. As I understand it, NIFs utilizes C code with no main function. That is, that each call to a NIF is a one-and-done type of proposition.
Can someone give me some pointers on how (assuming it is appropriate) one can utilize NIFs to interact with C code that needs keeps state across multiple calls? I hope that was clear!
Check the documentation for resource objects. The NIF API even allows you to use the erlang GC to GC the lists you create should the process which has created it crash!
the 'static' variable in C can keep value between calls, but I would strongly dont recommend this way. If you need some state, it would be better to look at 'ports' in erlang.

Usage of inline closures / function delegates in Actionscript

Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.
I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.
Are there any catches of using them? Do they work pretty much the same way as in C#.
I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!
private function showPanel(index:int):void {
_timer = new Timer(1000, 1);
_timer.addEventListener(TimerEvent.TIMER, function(event:Event):void
{
// show the next panel
showPanel(index++);
});
The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.
But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.
Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).
Hope this helps.
One additional problem is that garbage collection is broken when it comes to closures (at least in Flash 9). The first instance of a given closure (from a lexical standpoint) will never be garbage collected - along with anything else referenced by the closure in the scope chain.
I found what originally made me NOT want to do this, but I had forgotten the details:
http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539
(This is what Mitch mentioned - as far as the 'this' keyword being out of scope)
So thats Adobe's answer, however I am much more likely to need to refer to local variables than 'this'.
How do others interpret Adobe's recommendation ?

Resources