23 September 2007

Pensieri di un uomo assonnato

Si ecco, mi trovo ancora una volta a pensare a questa situazione sentimentale...
... Che sono cambiato, non c'e' dubbio. Non sono piu' tollerante come prima... Non riesco piu' a stare dietro a chi mi rincorre, mi dispiace. So che non e' bello, ma ho scelto una strada e per ora non mi pento della scelta.
Altro e' cambiato, pero'. Ad esempio, non mi sento piu' freddo e vuoto... Ho riscoperto un timido sentimento d'affetto, verso tre donne.
Una ormai la conosco da un po', l'altra la conosco da un po' meno e l'ultima da poco.
Sono tre sentimenti diversi, che non mi sono mai mancati, ma che mi fa molto piacere riscoprire... Amicizia, fratellanza, complicita'.

Finalmente riscopro l'emozione di provare qualcosa, un interesse che non sia un banale accenno, ma che sia un pensiero quasi fisso. Una amica che sento amica, una ragazza che sento vicina, una persona che mi attrae. E' proprio bello.

Peccato che assieme a tutto questo ritornino gli inevitabili risvolti negativi... E naturalmente il mondo degli eventi si allarga (gia', ora non ci sono solo io. Siamo noi). Insomma... Andra' bene? Andra' male? Che capitera' con lei? Lei scegliera' me?

La mia voglia di essere single sta scemando, ho voglia di cambiare e mi sembra il momento ideale per farlo. Non perche' mi pento delle mie scelte passate (anzi, senza questi sentimenti forse le rifarei anche), ma perche' finalmente mi sento ad un punto importante della vita in cui e' giusto che subentri qualcuno. Non mi va piu' di correre tra cento donne che spariscono nel giro di poco.

Voglio emozionarmi ancora, per una donna sola.

E ora, dopo diversi anni, mi sento di riuscirci ancora.

Speriamo bene :)

18 September 2007

Thousand uses of a Bic :)

Well, after a chatting with my dear Vaniglia, it ended up that a bic has 1000 uses.
So, open this log to write down some of these uses, hoping that you will add some comment adding the remaining 900 (and maybe more) uses :D

  1. Blowgun

  2. Screwdriver

  3. Hairslide

  4. ... Else?



Have fun :)
Stay --sync

16 September 2007

Yoho 1.0

Dehehe I just made 3 concurrent objects forward a message in circle.
The interface is a bit rude now... Actually user have to deal with a shared pointer-to resource, which share a pointer to the data :D It's a bit dirty, but does the job.
I can clean it and make straightforward it's use. For now, user's code looks like this:

class Ring: public Thob::Thom {
/* Using these data won't work.
* They are copyable, but not shared between copies of this object.
Ring *_next;
std::string _name;
*/
// Using resource class
boost::shared_ptr<Thob::Thor<Ring *> > _next;
boost::shared_ptr<Thob::Thor<std::string> > _name;
public:
Ring():
_next(new Thob::Thor<Ring*>(new Ring*(NULL))),
_name(new Thob::Thor<std::string>(new std::string("Unkn"))) {
std::cout << "Ring " << **_name << " ctor\n";
}
Ring(const std::string &name):
_next(new Thob::Thor<Ring*>(new Ring*(NULL))),
_name(new Thob::Thor<std::string>(new std::string(name))) {
std::cout << "Ring " << **_name << " ctor\n";
}
void setNext(Ring *n) {
std::cout << "Ring " << **_name << " setting next " << **n->_name << std::endl;
**_next = n;
}
void process(const Thob::Message &m) {
cout << **_name << " has received a message\n"
"\tid: " << m.id << "\n"
"\tcont: " << boost::any_cast<std::string>(m.data) << "\n"
"\tfrom " << m.source << "\n"
"\tForwarding to " << **_next << "\n";
(**_next)->enqueue(m);
}
};

/* In main */
Thob::Thol<Ring> a("A"), b("B"), c("C");
a->setNext(&);
b->setNext(&c);
c->setNext(&a);
a->enqueue(Thob::Message(1, std::string("Messaggio"), NULL, NULL));

a.join();
b.join();
c.join();
The reason for such complicated resource managing is that data, to be shared between threads, must be global or on heap (and of course heap is preferred). This lead to the first pointer. This pointer is then managed by Thor (Thread Object Resource), which apply a mutex and locking on it. Err, actually I didn't used locking on this example, but it's aviable :D Thor *manages* a resource, but actually it's another object. And it's non-copyable, since it have boost::mutexes in it. So, since you want to use one resource manager for each resource data, you probably want to share this resource manager with a shared_ptr.
This leads to complicated code. So this afternoon I'll try to remove it.

Thol is the Thread Object Launcher, it is necessary because is a bad practice to make thread objects self runnable, because it may lead to thread referencing incompletely constructed objects.

Anyway, these seems to be the classes involved in the process (i.e. what the user will have to deal with):

  1. Thob: Thread Object (namespace)

  2. Thom: Thread Object Manager - Handles messages exchange and processing

  3. Thor: Thread Object Resource - Handles access to a shared resource between threads

  4. Thol: Thread Object Launcher - Constructs a Thom object and make it runnable



Later I'll fix some syntax, do other tests... And maybe publish the code ;)

Stay --sync

15 September 2007

Pointers to members in C++

Well, from the documentation found around, I guess that this isn't a much used feature of C++. Actually, C's pointers to function was almost 1337 feature, and thus the same must be in C++. Actually, in C++ it's even more complicated, because we have... Classes! Thus we need to reference a member of a class. And this class may have children! How about them? How are them handled?
Well, I didn't find an answer to all these questions, so I wrote my code and tried to see what's happening.

The first thing to remember is: when dealing with classes, you're dealing with offsets. In fact, to reference a member of a class, you don't dereference the pointer, but use the scope resolution operator. First, this is the test class:
struct Test {
int a, b;
Test(): a(0), b(0) {}
void fun(int x) { b = x; }
void gun(int x) { a = y; }
};
Now take a look on how you can reference the a property:
Test o;
int Test::*p = &Test::a;
std::cout << o.*p << endl;
See? first: this is a pointer to a member of Test, thus we don't write int *Test::p (because Test::p is just nothing). And to get the address, we do use the scope resolution operator: &Test::a.
This is quite simple: resolve the class Test and get the offset of the a property. Yeah. But, offset respect to *what*??
Actually, to reference a real, instanced, integer, we need an instance of Test: Test o. Then, we need to lookup in *that* object for the given offset. We need to refer the object and dereference the pointer. We use the .* (and ->*) operator(s).

Actually, if we're dealing with properties (i.e. not methods), we can also refer directly the object and it's field:
int *p = &o.a;
I don't know if this is allowed in C++ standard, but gcc4 compile it with no warnings.

Similar is with methods: we *need* to refer to the class' offset and then apply it to an object:
void (Test::*f)(int) = &Test::fun;
(o.*f)(123); // Refer and dereference
// void (*f)(int) = &o.fun; // Not allowed.

Does it work something mixed?
int Test::*p = &o.var;
No, because o.var doesn't refer to object's offset, while Test::*p does.

Now, let's try with a child object:
struct Child: public Test {
int c;
void fun(int x) {}
};

Child s;

int Test::*p = &Child::a; // This is ok
// int Test::*f = &Child::c; // !!! Illegal !!!
void (Test::*g)(int) = &Child::gun; // Also this is ok
// void (Test::*h)(int) = &Child::fun; // !!! Illegal !!! (X)
void (Test::*h)(int) = &Test::fun; // Ok, of course

The first is ok, because we're referencing the a property, which is inherited from Test, thus the Child::a is a valid object when downcasting to Test::a. The second is not valid! Because c is not present in Test, but only in Child. The third is ok, because gun() is inherited from Test. The next one (marked with X), however, doesn't work: it's not allowed a conversion from Child::* to Test::*. Thus, we need to use &Test::fun, but we can of course call it using child's pointer:
(s.*h)(123);
It's also interesting to see how virtual doesn't changes the X's behavior. If you set fun() as virtual in Test, the fourth example above won't work. I'm not sure why this happens, but I guess it's something related to pointers and vtables: when you don't use a pointer, referencing the object and the method, C++ will lookup the vtable (if present, of course) to find the method to call. When dealing with pointers, we know the offset of the function to call. So it just perform type checking on pointers, but doesn't lookup for vtables.

Well, these are just ideas. Remember that they may be *totally* wrong. I'm writing these things at 2:32 (not 14:32 :P), so my mind maybe obfuscated :D I'll take a look to C++ standard, hoping to remember to patch this log. Meanwhile, if some C++ guru wants to explain/correct me, he's welcome.

Stay --sync

13 September 2007

New-oh!

Yoho! Coarse, but there is the new, official, template :D
If you're using a feed reader, probably you need to go on the blog's page to see it... And actually lots of things are missing: all details about me are lost, all links, no navigation, no comments... This is a pure blog: cat /var/log/blog | format --nice --HoE

Too nerd. AhAha

I only hope to be able to do what I'm thinking with the tools give by blogger.com... Actually, I can use the blogger's API for data retrieval and write the rest with php. We'll see. Blogger's template capabilities seems powerful, but actually not well documented, so I don't know how much it's possible to do.

Uh, probably I'll also add some javascript modifications to the home page... We'll see.

Stay --sync

Ipersimple remote shell with netcat

Sometimes you may need to have a very very raw, but working, remote shell. I mean, something that's really simple, and can be done with a single command (even if more complex scripts exists).
Actually, I need to setup a shell in a easy way, no password is needed, just a command line via netcat.
mkfifo inp; nc -lp 2000 < <(bash <inp 2>&1) >inp ; rm inp
If you got it, ok. Else read the explanation:
  • Idea: let's redirect both stdin and stdout of netcat to a shell, in a short command, if possible.
  • mkfifo inp this simply creates a FIFO (a.k.a. named pipe) node. If you don't have pratice with FIFOs, you may wonder why using it and not just a regular file. Easy: FIFOs are opened both for reading and writing, allowing process inter-comuncation. A regular file isn't consumed while being read. If you try with a touch instead, it won't work.
  • <(bash < 2>&1) This is a subprocess substitution. This mean: bash will execute the commands between parenthesis (the subprocess) in a different shell. Then will create a temporary fifo that will contain the commands' output. The path of the fifo (a filename) will be substituted to the whole command.
  • From the above, you can understand why I did < <(bash...): <() becomes a filename, thus the whole command becomes: nc < /dev/fd/63. As you guessed, /dev/fd/63 is the file descriptor for the temporary fifo of the subshell. In this way, the output of the subshell will be used as input of netcat.
  • This isn't sufficient, we need to redirect netcat's output to subshell's input. This is done with bash <inp and >inp
To be verbose I'll tell you even because I need this command. Probably this is a stupid way to do it, but if it works....
Problem: two hosts, one (we'll call it B) is behind a firewall and can't get incoming connections, but can go out without problems. It happens that B doesn't have any server on it, but A has a ssh server. I want to access B from A. Since it would be a bit hard to access B without any server on it (lol), let's say that B is your office's workstation, and you have manual access on it, but when you go home (A) you want to connect to B and use it remotely. How? Easy :D The above script and ssh port forwarding:
B$ screen # if you want to do logout and detach this session leaving the server running
B$ (mkfifo inp; nc -lp 2000 < <(bash <inp 2>&1) >inp ; rm inp) &
B$ ssh -R 2222:localhost:2000 address_of_A cat - # cat - is used to keep the connection alive
password:
B$ C-a d # if using screen, you may want to detach
Now on B we have enstablished a connection with ssh to A with port forwarding over a secure channel. If you don't have pratice with -R and -L flags of ssh, read them like this:
  • -R 2222:host:2000 = "on the Remote host, listen on port 2222 and forward (locally) to host:2000" that is, on the host we're connecting to, there will be a port 2222 that will accept connection as it was the port 2000 on the host
  • -L 2222:host:2000 = "on the Local host, listen on port 2222 and forward (remotely) to host:2000" that's like above, but with swapped targets.
In our case, we need that the netcat shell is accessible on the remote host A, so we need the -R flag.

At home, on A, we can connect to a local remotely-forwarded-shell on the port 2222:
A$ nc localhost 2222
echo "Every message written here, will be executed on the remote side"
exit
The only problem is that (I don't know why) the prompt message isn't written on netcat. So you won't see:
bash> echo "Some commands"
but just the commands you're writing.

Use it wisely.

Edit: Yes *of course* you can use -e /bin/bash with netcat instead of using fifos... But actually there are two reasons why I wrote this tip: first, not every distribution of netcat (e.g. emerge netcat) is given with -e, which is considered dangerous (I don't know why, but I saw it often with alerts signs, not only on gentoo), second, I wanted to refresh my memory and spread the knowledge of process substitution. I mean, this just allow *any* stdin/out program to have an -e option. The power in this tip is not netcat, but process substitution. Netcat is here just as example.

Edit 2: As Drizzt noticed, this version works on bash (yah, I'm a bash-man :D), and not, for example, on sh. I proposed that using pipes does the job:
mkfifo in out; nc -lp 2000 <in >out ; bash <out >in ; rm in out
He proposed a shorter version, which uses the existing pipe command:
mkfifo fifo ; netcat -lp 2000 <fifo | bash -i &> fifo ; rm fifo


Stay --sync

10 September 2007

Ar-smileys 1.9 bugfix

TigrisWillow found a bug into theme file of ar-smileys 1.9b: the degree character (°) was not correctly recognized, so I switched to the ASCII single quote (').
So it will be :'D and :'), but the old :°D will works as well.

Get the AR-Smileys 19c theme for pidgin/gaim/kopete

Thanks TigrisWillow!

Stay --sync

Concurrent Object Oriented Programming - Part I

Well, as you may know, I'm working on a model of coop, in C++ and Boost, which should ease the object oriented programming with threads.

Yesterday night I worked on a first model, implementing also a shared/count_ptr which deallocates the memory when no reference to the objects are present.
Problems:

  1. shared_ptr was already present in boost XD But I don't like it... For example, my implementation keep has the operator=(T *ptr), so you can do:
    count_ptr<int> p(new int(10));
    p = new int(20);
    count_ptr correctly deallocates the first resource and set the second. With the standard compliant pointers there is no such operator, and you have to use reset(T *) (if someone can explain me why, I'm curious to know).

  2. Even using just pointers, the code wasn't thread safe (see the thread object code). Actually, the message queue has a mutex for accessing it, but the rest of the object... haven't! In addition, multiple threads can access object's memory without control.
    So, the idea is to create a new class Resource, which contains the user object in single instance. This class will also count the number of references to it, and it will also act as proxy, controlling the accesses to the resource. It will eventually use a global mutex to lock the whole resource.

So, I'm going to rewrite this code and make it much better... It will be a really neat work with smart pointers ;)

Stay --sync

Nerd-test 2.0

Ahaha the second version XD (following drizzt, thanks)


NerdTests.com says I'm a Cool Nerd God.  What are you?  Click here!


c.v.d. :)

EDIT: Ho fatto ancora quello vecchio... Sono aumentato di 2 punti XD


I am nerdier than 100% of all people. Are you a nerd? Click here to find out!


Stay --sync

Dehehe I must tell this someone :D - Part IV

Well... Again on the thread project:
actually the pointer method seems to work: all resources are shared among Boost.threads using a count_ptr (yes, other smart pointers of this type may exists, but I reimplemented it from scratch. This is my first smart pointer, so I hope it's ok).

I got 2 segfaults, fixed, because I was doing silly things:

  1. Created a boost::thread(*this) before creating other resources: remember that if an object is copied and it's data are shared, you need to create all data before copy it, or you'll have multiple data and not multiple pointers.

  2. Join was mis-used: it must be called from parent thread, which waits the end of the child execution. I called join() both into the children and the parent


Now, a simple base code is working. I'm tired now, so I'm not publishing it (also because this is just basecode, while you may be interested also into an example implementation) for now. I need to put also copyright notes in it -_-'

Stay --sync

07 September 2007

Proudly member

Pepeerepeeeee'

http://member.acm.org/~akiross should be self explanatory :)

The first paper I'm reading is about garbage collection :)

A new era of knowledge starts now, without limits.
Stay --sync

About auto_ptr

I found a really clear and interesting article:

How to use auto_ptr effectively in C++

Great.

Stay --sync

06 September 2007

Dehehe I must tell this someone :D - Part III

Well, after writing down a draft with my ideas (maybe I'll publish it later), and a quick prototype in C++ and Boost.thread, I found out that it's quite an hard task:
Actually with Boost you can create a thread with a functor, like this:

struct Object {
void operator()() {
// Here thread body
}
};

boost::tread t(Object());

Well, this is great for many reasons: for example, using a functor instead of a callback function like in pthreads gives much more power, starting from the fact that you can add arbitrary data with your function, ending with the fact that you can actually write your own object and just put it in a separate thread.
Well, on the other hand:

struct Object {
void operator()() {
std::cout << "Executing in a different thread\n";
}
Object() {
std::cout << "Creating a new Object\n";
}
Object(const Object &o) {
std::cout << "Copying an existing Object\n";
}
};

boost::thread t(Object());

/* Here, it outputs:
Creating a new Object
Copying an existing Object
Copying an existing Object
Copying an existing Object
Copying an existing Object
Copying an existing Object
Executing in a different thread
*/

If you don't know boost's thread library, you may wander "why a copy constructor?". Well, when creating a thread object, it'll be copied into an internal memory location of the execution thread.
This is bad, to me. First, because your code may have problems when copying if you don't know what boost.thread will do with your functor, second because you may prefer to don't copy it at all. Third, of course it avoid use of non-copyable objects.

Don't ask me why (I didn't look the library's code, yet) the object is copied, and don't ask me why it's copied *five* times.
I hope to have time to give it a look, tomorrow or in the week end... But I found it silly to copy the object: threads share the heap and static memory, so one could easily just allocate the object in the heap and refer it everywhere! I can't see the need to copy it to an internal location.

The only think I can guess right now is just matter of portably: Boost.thread is created with multi platform in mind, so it try to use (and you can see this from the few APIs it provides) the most common and universally known threading features available on the majority of multi-threaded platforms. It doesn't even give the thread's ID, probably because some systems just don't give an ID to threads.

Probably I'm not the most skilled programmer, but I find it hard, if not impossible, to avoid the copy of an object. I mean: of course everyone knows how to make it non-copyable, but boost.thread need it to be copyable, so we just can't make it private.
Since the library actually call the copy constructor, it means that another object _is_ allocated. So, even if you make all dynamic and copy your pointers around, another object will exists.

This could be a solution:

class Object {
type *_dataPtr;
int *_instances;
public:
Object() {
_dataPtr = new type;
_instances = new int(1);
}
Object(const Object &o) {
_dataPtr = o._dataPtr;
_instances = o._instances;
++(*_instances);
}
~Object() {
if (--(*_instances)) {
delete _data;
}
}
void operator()() {
// Blah
}
};


The idea (hoping the code is correct, but the important thing is the idea :P) is to create objects which are just "interfaces" to data. This means that data are created just with constructor and not copied.
Yes, this may work... But i find it rather ugly. Of course it would be a nice is a wonderful idea to use auto_ptr or something similar for these pointer stuff.

In this way, you can still have multiple instances of your objects in memory, but accessing always the same data.
Of course, this means that you may need to handle also this level of parallelism, since the object code will be executed by the launching thread: when handling messages, it's done in the new threads, when you do it, it's done in the main thread.

Luke, now you have the force. Use it wisely.
(ahahaha)

Stay --sync (and keep your objects sync'ed too)

02 September 2007

Dehehe I must tell this someone :D - Part II

Well, after getting sane I thought that probabily that was a _really_ insane idea.

So, after a quick preview of the ES4 draft specification, I decided I'll not write a new language, but just write an implementation of ES4 with multithreading in mind.

Yes, this is insane idea, but at least I'll not reinvent the wheel.

Stay --sync

01 September 2007

How much a person change

Some days ago I found a drawing made in 2003 or 2004. I remember it, was a draft, but I remember clearly that was almost my top.
I remember clearly that I was satisfied of it:

"Well, it's just a draft, but looks like what I mean to draw. Yes yes, I like it."

I said.

Some years later, I found that picture, and I said:

"bleah, let's see what can I do now."

And in 20 mins I made another draft.

You judge:



I say I got better :)

Stay --sync

Dehehe I must tell this someone :D

I'm writing a new language XD

The idea is... Ruby, with better syntax and native threads. The idea of a language with threads deeply into it was in the air since long time (in _my_ air :) and now I finally decided how it should do.
I'm mostly defining it "by example": how should one do X? Is this syntax necessary? Can I avoid Y? Can it be shorter and quicker? And adding some features that I found missing in other languages.

Of course, the idea is a C-like synax (I just find it readable, that's all), but since it's intepreted and it's highly dynamic, it's almost upsetted.

The other projects... Well, I'm not saying anything yet :) Top Secret!

Hey, I'm getting crazier :D

Stay --sync