Subscribe:
    Subscribe Twitter Facebook

    Saturday, December 18, 2010

    Locked internal resources (why it wouldn't work :) )

    A few days ago I shared this evil template with you:


    template
    class locked_object : boost::noncopyable
    {
    T *object;
    TLockable *lock;
    bool locked;

    public:
    locked_object(T *_object, TLockable *_lock) : object(_object), lock(_lock), locked(true)
    {
    lock->lock();
    }

    ~locked_object()
    {
    lock->unlock();
    }

    T *get()
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");
    return this->object;
    }


    void unlock()
    {
    locked = false;

    lock->unlock();
    }

    T *operator ->() const
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");

    return this->object;
    }

    operator T *() const
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");

    return this->object;
    }
    };


    I asked for advice on StackOverflow on the matter and got some very valuable input indeed. The problem with this class is that I trust the programmer to follow the semantics and the protocol of this template which are:

    * Never save the pointer for latter usage
    * Never use the object after you call locked_object<>::unlock()

    Well obviously this template solves nothing :) It doesn't prevent the programmer doing sinful things. The programmer might do his best to follow the intended protocol yet a small error may introduce a bug that is very hard to detect and/or reproduce.

    Moreover, I learned about the Law of Demeter which implies you never should let anyone "dig the guts of an object" (How could you ever do that safely ? :) ). And with my naive and extremely faulty approach I now fully grasp the idea. The good thing is this class hasn't made its way into any production code.

    Let's close it with a meaningful saying;

    To rise from error to truth is rare and beautiful.
    Victor Hugo

    Tuesday, December 14, 2010

    Locked internal resources (digging the guts of your class safely)

    Disclaimer: See this after reading.

    Just stopped by to share this template class that I've written to expose internal data members of a class in a thread-safe manner.


    template <typename T, typename TLockable = boost::mutex>
    class locked_object : boost::noncopyable
    {
    T *object;
    TLockable *lock;
    bool locked;

    public:
    locked_object(T *_object, TLockable *_lock) : object(_object), lock(_lock), locked(true)
    {
    lock->lock();
    }

    ~locked_object()
    {
    lock->unlock();
    }

    T *get()
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");
    return this->object;
    }


    void unlock()
    {
    locked = false;

    lock->unlock();
    }

    T *operator ->() const
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");

    return this->object;
    }

    operator T *() const
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");

    return this->object;
    }
    };



    Usage semantics are fairly easy. You keep your data private and define an accessor e.g. getData() and return a locked_object<> from this method. When the locked_object<> goes out of scope it will release the lock, letting other waiting threads reach the resource. You just have to pass a pointer to your data member and a pointer to a synchronization primitive that has lock() and unlock() methods. See the infamous example class Foo sharing a file handle with several other threads.


    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>

    #include <boost/shared_ptr.hpp>
    #include <boost/noncopyable.hpp>
    #include <boost/thread.hpp>

    template <typename T, typename TLockable = boost::mutex>
    class locked_object : boost::noncopyable
    {
    T *object;
    TLockable *lock;
    bool locked;

    public:
    locked_object(T *_object, TLockable *_lock) : object(_object), lock(_lock), locked(true)
    {
    lock->lock();
    }

    ~locked_object()
    {
    lock->unlock();
    }

    T *get()
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");
    return this->object;
    }


    void unlock()
    {
    locked = false;

    lock->unlock();
    }

    T *operator ->() const
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");

    return this->object;
    }

    operator T *() const
    {
    _ASSERT(locked);
    if (!locked)
    throw new std::exception("Synchronization error ! Object lock is already released !");

    return this->object;
    }
    };

    std::vector<boost::thread> thread_list;

    class Foo
    {
    boost::mutex out_lock;
    boost::shared_ptr<std::ofstream> file;


    public:
    Foo() : file(new std::ofstream("important_file.txt", std::ios::trunc))
    {
    _ASSERT(file->is_open());
    }

    locked_object<boost::shared_ptr<std::ofstream> > getOutLocked()
    {
    return locked_object<boost::shared_ptr<std::ofstream> >(&file, &out_lock);
    }

    std::ofstream& getOut()
    {
    return *file;
    }
    };

    Foo f;

    void fn_thread(int i)
    {
    /* Non thread safe */
    f.getOut() << "What ";
    boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    f.getOut() << "can I do ";
    boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    f.getOut() << "sometimes ?\n" ;
    /* */

    /* Thread safe
    locked_object<boost::shared_ptr<std::ofstream> > lout = f.getOutLocked();

    (**lout) << "What ";
    boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    (**lout) << "can I do ";
    boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    (**lout) << "sometimes ?\n" ; */
    }

    int main()
    {
    for (int i = 0; i < 50; ++i)
    thread_list.push_back(boost::thread(boost::bind(fn_thread, i)) );

    for (std::vector<boost::thread>::iterator it = thread_list.begin(); it != thread_list.end(); ++it)
    if (it->joinable())
    it->join();

    return 0;
    }


    When you run the above code as is, the threads will race for the file resource and the program will yield corrupt data like;


    What What What What What What What What What What can I do can I do can I do can I do can I do can I do can I do can I do What can I do What What What What What What What What What What What can I do What can I do can I do sometimes ?
    sometimes ?
    can I do can I do can I do sometimes ?
    sometimes ?
    can I do sometimes ?
    can I do can I do sometimes ?
    sometimes ?
    can I do can I do sometimes ?
    sometimes ?
    can I do can I do What What What What What What What What What can I do can I do sometimes ?
    sometimes ?
    sometimes ?
    sometimes ?
    sometimes ?
    .
    .
    .


    In contrast, if you comment out the Not thread safe block and make the Thread-safe
    block active in the fn_thread() function the output will be;


    What can I do sometimes ?
    What can I do sometimes ?
    What can I do sometimes ?
    What can I do sometimes ?
    What can I do sometimes ?
    What can I do sometimes ?
    .
    .
    .


    as expected. I would love to hear any opinions about the code and potential problems it may bring. What if our shared resource is not a simple handle but a complex tree structure where references to sub-nodes can be passed to other components of our program ? What synchronization issues would this locked_object<> pose ? How can we eliminate them ?

    Thank you for your time !

    And as you all know; Everything is something happens...

    Cheers!

    Saturday, June 26, 2010

    Observer pattern in C++ (without virtual functions)

    Yesterday I was trying to implement the observer pattern for use in a project of mine. The classes needed to be generic, type-safe, fast and easy to use. Asking too much ? Well no, not in the realm of C++ :) To retain type-safety I had to incorporate static polymorphism . That means virtual functions were to be dumped for good... They force you to make dangerous type casts causing some nausea :) . This was the first thing that I typed into the editor without thinking :)

     
    // A first and naive shot at the problem

    #include < list>
    #include < boost/bind.hpp>
    #include < boost/function.hpp>
    #include < boost/foreach.hpp>

    template < typename TObserver, typename TSubject>
    class observer
    {
    public:
    void observe(TSubject& s)
    {
    static_cast< TObserver *>(this)-> do_observe(s);
    }
    };

    template < typename TObserver, typename TSubject>
    class subject
    {
    public:
    typedef observer< TObserver, TSubject> observer_type;

    private:
    std::list< observer_type *> observers;

    public:
    typedef observer< TObserver, TSubject> observer_type;

    void add_observer(observer_type *po)
    { observers.push_back(po); }

    void remove_observer(observer_type *po)
    { observers.remove(po); }

    void notify_all()
    {
    BOOST_FOREACH(observer_type *po, observers)
    {
    po-> observe(*static_cast< TSubject *>(this));
    }
    }
    };


    As with all "typing without thinking" practices, this piece of code yields a disappointment :) The idea is that your "concrete observer" will derive from the observer class. So it will be parameterize with its own type and the subject type . The subject template also needs - two - types to resolve the function call observe() . But this means for each type of observer you must define a new type of concrete subject.

    e.g.

    // Forward declaration
    class model;

    class view : public observer< view, model>
    {
    public:
    void do_observe(model& m)
    {
    std::cout < < "view observed the model." < < std::endl;
    }
    };

    class controller : public observer< controller, model>
    {
    public:
    void do_observe(model& m)
    {
    std::cout << "controller observed the model." < < std::endl;
    }
    };

    // Here comes the problem..
    class model : public subject< view /* oh oh !? */, model>
    {
    };


    See the declaration of class model ? With this declaration a "model" object can only accept a "view" object as an observer.

    After experimenting a bit, I was convinced that this is a bit hard to solve (at least with my current knowledge). The main problem is that your concrete subject can notify only a single type of observer. If we were to use virtual functions, there would be no limitation on what type of observer we could use with the subject as long as our concrete observer were derived from the abstract observer. But we don't want it because we want type-safety and performance ;). So how to achieve it ? Let's summarize everything :)


    Subjects can only notify a single type of observer. Moreover observers and subjects must be strongly typed so the programmer won't be able to register an observer operating on apples with a subject representing an orange :)


    My point of view is that I should encapsulate the -operation- while satisfying the above requirements. The solution I came up with is to keep a list of function objects representing the operation - observe(). So here is the code for the pattern;


    // observer.hpp

    #ifndef OBSERVER_HPP
    #define OBSERVER_HPP

    #include < list>
    #include < boost/bind.hpp>
    #include < boost/function.hpp>
    #include < boost/foreach.hpp>

    // Forward declaration for subject
    template < typename TSubject>
    class subject;

    template < typename TObserver, typename TSubject>
    class observer
    {
    public:
    void observe(TSubject& s)
    {
    static_cast< TObserver *>(this)-> do_observe(s);
    }
    };

    template < typename TSubject>
    class subject
    {
    public:
    typedef boost::function< void (TSubject& ) > observer_type;

    private:
    std::list< observer_type > observers;

    public:
    template < typename TObserver>
    void add_observer(observer< TObserver, TSubject>& o)
    {
    observer_type o_fn = boost::bind(&observer< TObserver, TSubject>::observe, boost::ref(o), _1);
    observers.push_back(o_fn);
    }

    protected:
    void notify_all()
    {
    BOOST_FOREACH(observer_type o, observers)
    {
    o(boost::ref(*static_cast< TSubject *>(this)));
    }
    }
    };
    #endif


    STL and boost creates miracles for sure :) Let's have a look at the semantics of these templates. A concrete subject will derive from the subject class and when it's modified will call the notify_all() function internally. A concrete observer needs to derive from the observer class and must define a public do_observe() function which will operate on the concrete subject. Let's see the example client code;

    A simple implementation of MVC pattern with our observer templates. (I promised for one pattern and you get two ! Yay ! )


    // main.cpp
    #include < iostream>

    #include "observer.hpp"

    class model : public subject< model>
    {
    public:
    model()
    {
    std::cout << "model constructed\n";
    }

    void modify_model()
    {
    this-> notify_all();
    }
    };

    class view : public observer< view, model>, public subject< view>
    {
    public:
    void do_observe(model& m)
    {
    std::cout << "view observed the model" < < std::endl;
    }
    };

    class controller : public observer< controller, model>, public observer< controller, view>
    {
    public:
    void do_observe(model& m)
    {
    std::cout << "controller observed the model" << std::endl;
    }

    void do_observe(view& v)
    {
    std::cout << "controller observed the view" << std::endl;
    }

    };

    int main()
    {
    model m;
    controller c;
    view v;

    m.add_observer(v);
    m.add_observer(c);

    v.add_observer(c);

    // when the model is modified all its observers will be notified
    m.modify_model();

    return 0;
    }


    So tell me what you think. I'm eager to hear a better solution or any suggestions to improve this one. If there are any problems with the above code that I can't see please comment so we can discuss. Thanks in advance ! :)

    Friday, June 25, 2010

    The struggle to increase productivity

    Hi ! Yesterday I've installed Subversion on my computer to better manage my projects. I must say it's a relief :) The most useful thing for me so far was the ability to "branch" projects. So I can make some experimental changes without having to copy files and folders here and there. Changelogs, versioning etc. makes everything easy to track. I'm using VisualSVN . Very easy to setup and get going. Keeping track of what's done and what's next is what drives a project forward. Obvious... But grasping the concept requires time as usual :) . I'm using pen and paper, old fashioned and romantic in a way. Writing reports or short notes about where you are and what's your current destination is a good practice. Thanks to Peter (my boss and mentor :) ), I'm learning yet another aspect of software engineering. It's not just diagrams and documents, it's measuring the progress (which is really harder than design and documentation).

    Also, started to get a good grip of boost and STL. My C++ skills are increasing day by day ! If you're developing Windows applications you should definitely learn ATL and WTL (Did I ever mention this ?) . And here comes a cliché advise as usual :) Read source code !! There are so many awesome programmers who are so generous to share their work. Read some source code before you start a project. That's how I leveled up during the past few months :) . So make yourself a favor, take a cup of your favourite refreshment and visit SourceForge , CodePlex . That's it for now. I'll just enjoy some morning coding accompanied by the sweet summer rain...

    Cheers !

    Sunday, April 04, 2010

    A Change of Pace

    Greetings from your favourite procrastinator ! I want at least a few blog entries between my two summer vacations :) . So I'll just try to give a quick status report and a boring treatise on software development hehe :)
    So, I haven't finished that game I was doing with SDL. Well, the reason is I don't want to create a stupid clone (I'm lying I have a serious problem about focusing :) ) . So I ceased working on it after 5 hours into development :) I wanted to polish my graphics programming skills for some time since GFX technology is running forward like crazy as usual and I'm so much behind all that stuff (Boy where was I ??)... So nowadays I'm focusing on DirectX 10 and making small demos without the stupid software engineering crap. And the good thing is that the practice pays off instantly ! :) Because I'm not trying to build that perfect resource management system since I'm dealing with only a handful of resources. At the start it felt a bit weird but later on I realized that's the way it should be. This state of mind geared my brain up and let me put more on the screen. Here is my recipé for a change of pace for all us perfectionist software benders;
    First thing to carve on your wall: You can't do software engineering on your own nor can you do it with a few friends. I guess I lost my magic somewhere along the path when I was doing enterprise software development. It's good to study the methods and concepts of large scale software development for every individual programmer focusing on whatever specific subject (Databases, network, AI...). But individuals and small teams can only produce small scale work since large scale work is simply labour intensive.

    Think big and you're doomed to desperation with all your fancy diagrams, empty interface definitions and countless layers of abstraction even for a simple operation an a few numbers hoping that by some miraculous ignition you're going to implement all your ideas with your lightning fast fingers... Well that generally happens in movies :) It doesn't mean you should restrain your thirst for good design. Just quench it responsibly, keeping in mind that your first mission is to get the job done :) Bear in mind that software can not be created big. It evolves into a bigger thing. The emerging development methods like Agile, Extreme Programming which are the craze for some time backs my conclusion I think.

    - But (a big fat but) -
    You should never forget that code is a valuable commodity and a human is always short of time. So you have to realize that redoing the same work you did the night before is a serious obstacle in front of your potential and productivity. There comes in the famous software engineering cliché: Reusability.

    Let's try to sketch the picture here. Every single step of your development journey must be rewarding in some way. You must get results which can be seen with your bare eyes. In my case I'm doing graphics programming. One of the very basic tasks is to create a window for your program. You can do it in many ways and you can put countless abstractions and make it so cross-platform that even a Martian can use it to create a Pong game running on her spaceship's computer. But who cares about aliens anyway ? Just put a freakin' window onto the screen. Create a simple class to handle the usual stuff. You don't have to parameterize every single detail a window has like fonts, icons or the little system buttons on the top right. Forget them... You just want to render something and you don't need those features for a long time. Look at your code and try to get an intuition of what it does. And ask yourself the following questions:

    1)Is your class easy to use ?

    2)Is it up to the task ?
    e.g. creating and destroying a window without trouble

    3)Does the usage feel natural ?

    If you can find satisfactory answers to these in a glimpse of an eye then move on. Get the job done. Let's elaborate these questions but bear in mind that I'm no guru and this is just my intuition I developed during my studies and work. So my point of view might be lacking in some departments :) So... Your objects should be easy to create, you should be able to use some defaults for creation for example. If you're writing a class to handle polar coordinates add support for the necessary mathematical operations so you don't have to put in redundant and ugly code accessing public members of the class everytime you use it. Making the underlying data type templated could come in handy. Overload the arithmetic operators to be able to write natural statements. Or in the case of the windowing class put a cast operator for the OS handle type so you can directly pass your window object as a parameter to OS functions. These things sometimes don't hit the eye at first glance can make your day better in the long run. You'll see that the practice will take only a few seconds as you get used to it :)

    Don't feel broken hearted if the components you develop don't seem to match their relatives grown up in an environment full of professionals who devoted decades to achieve their current experience. When you're finished with your project you'll have taken one more step towards that garden :)

    Well... Random thoughts over :) I'll be moving to a better place shortly so I can put in more stuff like source code, videos etc. Also more technical articles about image processing and graphics programming are to come.

    Stay cool and treat nice to your debugger !

    neurorebel out.

    Monday, January 18, 2010

    The Aftermath

    It's sad that another year has passed by quitely. Nevertheless I have done good things in 2009 like forming good business connections and being involved in absolutely wonderful projects. The year 2009 had its ups and downs, and though I have little to tell, I have absolutely grown up significantly in terms of knowledge and experience. Looking forward to do much better in 2010 :).

    I have the occasional pile of half-finished and half-started projects on my hard-drive since I started to learn SDL and Box2D recently for quickly making small 2D games. I had so much fun during December to tell the truth. It's like reviving old days with much more freedom and power with regard to my improved skill-set and equipment. I have some code to share but you can learn much more from an ordinary SDL game making tutorial so I'll save it till I finish the "game". It won't take long, I promise :). I had trouble finding art assets that wouldn't look lame together. So I have come up with a "theme" which would involve only so much "-art-work" that even I, a stupid programmer, can cut with a litte fiddling with Photoshop hopefully...

    The last 2 months have been occupied by obligations at the school (exams, projects etc..) And not being the best example of a "student", I'm having a hard time dodging all the debris professors are throwing onto my feet :).

    By the way, if you're a coder and addicted to sci-fi/cyberpunk theme, here is your fix (if you still haven't read it) :



    A cyber-punk thriller about a virus penetrating into the minds of hackers filled with lots of sarcasm about governments, corporations and religious cults. What more would you want ? :)

    Maybe you want to play a game filled with fun and gorgeous 2D artwork ? Well, here is my recipé :



    Cortex Command feels like "Worms in real-time" with RTS elements like resource management and unit building - not to mention the nice "physics" aspect and the cyberpunk theme of the game.



    World of Goo is (more than) a puzzle game which will captivate even the most hard-core gamer. I hate puzzle games really... But this one is simply brilliant. With fantastic level designs, sound, music and story, it sucks you in like a giant vacuum cleaner (be waried).


    These are my picks of the year. Try them, buy them, spread the word. And surely there are lots of pearls to find in the sea. So remember to check out The Independent Gaming Source !


    See you in a few weeks ;)

    Friday, October 23, 2009

    Syntax highlighting fever

    Well, just stopped by to share a tip on how you can avoid hurting your eyes while working on Visual Studio 2008. If you're coding for long hours in front of a widescreen LCD with full brightness you might be suffering some headaches like me. Check out Winterdom's nice color schemes; http://winterdom.com/2007/11/vs2008colorschemes

    The only change I've made to these settings files has been decreasing the font sizes. I'd like to see more lines as it becomes harder to keep track of lengthy code files by scrolling up and down frequently. If you don't like the font sizes just open the settings file in a good editor and change the FontSize attributes as you fancy. You can import the settings file from the Tools->Import and Export Settings... (pretty easy eh? :) ). Do not forget to backup your current VS settings by exporting them to another file in case anything goes wrong.

    This is the modified DesertNights settings file I use for your convenience along with a screenshot ;)

    http://ifile.it/v8c2ozd




    See you then !