While studying Understanding The Linux Kernel I came across reference counter in Kobject structure and container.
So, how does it helps to map these structures?
Given below is a pragraph from ULK 3rd edition.
The kref field is a structure of type k_ref consisting of a single refcount field. As the name implies, this field is the reference counter for the kobject, but it may act also as the reference counter for the container of the kobject. The kobject_get( ) and kobject_put( ) functions increase and decrease, respectively, the reference counter; if the counter reaches the value zero, the resources used by the kobject are released and the release method of the kobj_type object of the kobject is executed. This method, which is usually defined only if the container of the kobject was allocated dynamically, frees the container itself.
Similarly in some more context this reference counter was used.
I want to know the practical mapping of the reference counter.
key functions of a "kobject" is to serve as a reference counter for the object
in which it is embedded. As long as references to the object exist,the object (and the code that supports it) must continue to exist. low-level functions for manipulating a kobject’s reference counts are:
struct kobject *kobject_get(struct kobject *kobj);
void kobject_put(struct kobject *kobj);
Calling to kobject_get increments kobject's reference Counter and Returns a pointer to the kobject and if kobject is in the process of getting destroyed, this particular Operation Fails and kobject_get Returns "Null".
Similarly when the reference is to be released, the call to kobject_put decrements the reference Counter and frees the object.
Reference counting for struct dev can be implemented as follows:
struct kobject *dev_get(struct dev *p)
{
struct module *owner = p->owner;
struct kobject *kobj;
if (owner && !try_module_get(owner))
return NULL;
kobj = kobject_get(&p->kobj);
if (!kobj)
module_put(owner);
return kobj;
}
I hope this answer may help you in certain way to understand something about kobject and reference Counter :-)
Related
In almost every page of the Gtk documentation there are the following phrases:
The data is owned by the caller of the function.
The data is owned by the called function.
The data is owned by the instance.
What do they mean, and what is the implication for memory management (g_free or g_object_unref)?
(I've read Introduction to Memory Management in GTK+, but it doesn't seem to cover "owned by the instance".)
You should read this like so:
the data: The parameter, the returned value, etc.
is owned by X: X is responsible to clean up (in most cases, this means calling g_object_unref on the data) the data.
With this in in mind:
The data is owned by the caller of the function:
The gtk_application_window_new function works this way (as far as the application parameter is concerned). This means that memory management (i.e g_object_unrefing application) is to be done by the caller of gtk_application_window_new. See this example here. Notice that the caller of gtk_application_window_new, here main (through activate) is managing the reference count: it is calling g_object_unref on app.
The data is owned by the called function:
The gtk_application_window_new function works this way (as the returned value is concerned). This means that memory management of the returned GtkWidget instance is to be done by gtk_application_window_new itself. So no need to call g_object_unref yourself. See this example here: window is created by gtk_application_window_new but is never explicitly freeed. This id because the called function (here gtk_application_window_new) is taking care of this.
The data is owned by the instance:
The gtk_builder_get_object works this way (as far as the returned value is concerned). This means that the memory management of the GObject* returned is to be performed by the builder instance itself. Because of this, calling g_object_unref is not wanted. See this example here: The builder object is managed, but now the widgets returned by calls to gtk_builder_get_object. Even if written in C, GTK is object oriented. This means that instance, here, means the same as a class instance in most OO language.
So I create my class Cars. Then I make a variable(audi) for an object from my class cars. Everything is fine and dandy but I noticed that I can create an object(with an engine value of 50) without specifying a variable for it to be held in. So now how can I access that object?
#include <iostream>
using namespace std;
class Cars
{
public:
int getStatus();
Cars(int engine=5);
private:
int m_engine;
};
Cars::Cars(int engine)
{
m_engine=engine;
cout<<"A new car is made."<<endl;
}
Cars::getStatus()
{
cout<<m_engine<<endl;
}
int main()
{
Cars audi(10);
audi.getStatus();
Cars(50);
}
It depends on when you want to access the object.
Cars(50);
With this piece of code, you create a temporary object that lives only during execution of the current statement (i. e. until execution of your code passes the semicolon).
Cars(50);
// I want to access the object here
In this case: Too late. The temporary has already been destroyed and doesn't exist any more. No chance to get back to it. You can, however, use the object as long as it lives, e. g. call a member function on it or pass it to another function:
Cars(10).doSomething();
// but right now (after the semicolon), the car doesn't exist any more
doSomethingElse(Cars(12));
// again, the object got destroyed
Be aware that in above example, you created two distinct instances, each ceasing to exist when reaching the semicolon. Be aware, too, that the objects' destructors get called at this point of time.
You need to do it all together, like this:
Cars(50).getStatus();
Otherwise you won't have a way to refer to your car with 50 m_engine.
This temporary should be used with fidelity. Read more in What is an Anonymous Object?
You can't! It's already dead by the time you try. Cars(50) is a temporary, and its lifetime ends at the end of its full-expression -- that is, at the ;.
I'm trying to wrap my head around classes in AHK. I'm C++ dev, so would like to make use of RAII (__New, __Delete), but it looks like I miss some concepts since things look very contra-intuitive for me.
After some tries I came up with this simple example:
class Scenario
{
__New()
{
MsgBox, NEW
}
__Delete()
{
MsgBox, DELETE
}
}
scenario := new Scenario
scenario := new Scenario
scenario := 1
scenario := {}
scenario := new Scenario
Return
As a result I get the following messages:
NEW
NEW
DELETE
DELETE
Questions:
Why doesn't the object get destroyed during the second assignment? I'd assume the number of refs going to 0, no?
How come I get 2 destructions in a row? Where was that object stored meanwhile? How could scenario variable hold both references?
Why was not the third construction called?
Why doesn't the object get destroyed during the second assignment?
Garbage collection had not been triggered yet
I'd assume the number of refs going to 0, no?
References going to 0 does not necessarily trigger GC
How come I get 2 destructions in a row?
Garbage collection cleaned both references at the same time
Where was that object stored meanwhile?
The heap
How could scenario variable hold both references?
scenario does not hold both references
Why was not the third construction called?
Only two Scenario objects are constructed. The variable scenario is a dynamic variable and is not always an instance of the class Scenario. The last assignment scenario := {} just creates an empty object.
Ok, found out what was missing. Two things:
AHK script is case-insensitive.
Since class is an object by itself in AHK it's possible to override the class by another object.
Here is a piece of the documentation:
Because the class is referenced via a variable, the class name cannot be used to both reference the class and create a separate variable (such as to hold an instance of the class) in the same context. For example, box := new Box would replace the class object in Box with an instance of itself. [v1.1.27+]: #Warn ClassOverwrite enables a warning to be shown at load time for each attempt to overwrite a class.
This explains what happened in the code above: variable name scenario is effectively the same as a class name Scenario, so I just quietly overrode my class with an empty object.
Also, since the new instance of the class is created before assignment, I got two 'NEW' in a row, only than 'DELETE'.
I have a problem with Lua and I don't know if I going in the right direction. In C++ I have a dictionary that I use to pass parameter to a resource manager. This dictionary is really similar to a map of hash and string.
In Lua I want to access to these resource so I need a representation of hashes. Also hashes must be unique cause are used as index in a table. Our hash function is 64bit and I'm working on 32bit enviroment (PS3).
C++ I have somethings like that:
paramMap.insert(std::make_pair(hash64("vehicleId"), std::string("004")));
resourceManager.createResource(ResourceType("Car"), paramMap);
In Lua want use these resources to create a factory for other userdata.
I do stuff like:
function findBike(carId)
bikeParam = { vehicleId = carId }
return ResourceManager.findResource('car', bikeParam)
end
So, sometime parameter are created by Lua, sometime parameter are created by C++.
Cause my hashkey ('vehicleId') is an index of a table it need to be unique.
I have used lightuserdata to implement uint64_t, but cause I'm in a 32bit enviroment I can't simply store int64 in pointer. :(
I have to create a table to store all int64 used by the program and save a reference in userdata.
void pushUInt64(lua_State *L, GEM::GUInt64 v)
{
Int64Ref::Handle handle = Int64Ref::getInstance().allocateSlot(v);
lua_pushlightuserdata(L, reinterpret_cast<void*>(handle));
luaL_setmetatable(L, s_UInt64LuaName);
}
but userdata are never garbage collected. Then my int64 are never released and my table will grow forever.
Also lightuserdata don't keep reference to metadata so they interfere with other light userdata. Checking the implementation the metadata table is added in L->G_->mt_[2].
doing that
a = createLightUserDataType1()
b = createLightUserDataType2()
a:someFunction()
will use the metatable of b.
I thought that metatable where bounded to type.
I'm pretty confused, with the current implementation lightuserdata have a really limited use case.
With Python you have a hash metafunction that is called anytime the type is used as index for a dictionary. It's possible to do something similar?
Sorry for my english, I'm from Italy. :-/
I have a lookup table (LUT) of thousands integers that I use on a fair amount of requests to compute stuff based on what was fetched from database.
If I simply create a standard singleton to hold the LUT, is it automatically persisted between requests or do I specifically need to push it to the Application state?
If they are automatically persisted, then what is the difference storing them with the Application state?
How would a correct singleton implementation look like? It doesn't need to be lazily initialized, but it needs to be thread-safe (thousands of theoretical users per server instance) and have good performance.
EDIT: Jon Skeet's 4th version looks promising http://csharpindepth.com/Articles/General/Singleton.aspx
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
// randomguy's specific stuff. Does this look good to you?
private int[] lut = new int[5000];
public int Compute(Product p) {
return lut[p.Goo];
}
}
Yes, static members persists (not the same thing as persisted - it's not "saved", it never goes away), which would include implementations of a singleton. You get a degree of lazy initialisation for free, as if it's created in a static assignment or static constructor, it won't be called until the relevant class is first used. That creation locks by default, but all other uses would have to be threadsafe as you say. Given the degree of concurrency involved, then unless the singleton was going to be immutable (your look-up table doesn't change for application lifetime) you would have to be very careful as to how you update it (one way is a fake singleton - on update you create a new object and then lock around assigning it to replace the current value; not strictly a singleton though it looks like one "from the outside").
The big danger is that anything introducing global state is suspect, and especially when dealing with a stateless protocol like the web. It can be used well though, especially as an in-memory cache of permanent or near-permanent data, particularly if it involves an object graph that cannot be easily obtained quickly from a database.
The pitfalls are considerable though, so be careful. In particular, the risk of locking issues cannot be understated.
Edit, to match the edit in the question:
My big concern would be how the array gets initialised. Clearly this example is incomplete as it'll only ever have 0 for each item. If it gets set at initialisation and is the read-only, then fine. If it's mutable, then be very, very careful about your threading.
Also be aware of the negative effect of too many such look-ups on scaling. While you save for mosts requests in having pre-calculation, the effect is to have a period of very heavy work when the singleton is updated. A long-ish start-up will likely be tolerable (as it won't be very often), but arbitrary slow downs happening afterwards can be tricky to trace to their source.
I wouldn't rely on a static being persisted between requests. [There is always the, albeit unlikely, chance that the process would be reset between requests.] I'd recommend HttpContext's Cache object for persisting shared resources between requests.
Edit: See Jon's comments about read-only locking.
It's been a while since I've dealt with singleton's (I prefer letting my IOC container deal with lifetimes), but here's how you can handle the thread-safety issues. You'll need to lock around anything that mutates the state of the singleton. Read only operations, like your Compute(int) won't need locking.
// I typically create one lock per collection, but you really need one per set of atomic operations; if you ever modify two collections together, use one lock.
private object lutLock = new object();
private int[] lut = new int[5000];
public int Compute(Product p) {
return lut[p.Goo];
}
public void SetValue(int index, int value)
{
//lock as little code as possible. since this step is read only we don't lock it.
if(index < 0 || index > lut.Length)
{
throw new ArgumentException("Index not in range", "index");
}
// going to mutate state so we need a lock now
lock(lutLock)
{
lut[index] = value;
}
}