Quote of the week
Posted Dec 9, 2004 21:29 UTC (Thu) by
simlo (subscriber, #10866)
In reply to:
Quote of the week by iabervon
Parent article:
Quote of the week
I haven't looked at Ingo's patch, but any problems which prohibited a compile-time solution in C (probably passing locks of unknown implementation through another function) would also prohibit it in C++, and C++ would then general virtual function calls, which would then be prohibitively expensive for such fast-path code. The reason for doing that sort of ugly thing is really that you have a special case with critical performance, and you have to open-code such things in any language.
Ofcourse you wouldn't do it by virtual functions in C++! You use virtual methods when you want to branch out run-time, not compile time. In C++ you simply define two classes with the same public methods. In this case class spinlock and class mutex with public methods lock() and unlock(). Then all code can compile with no further change no matter if you declare your lock by "mutex mylock;" or by "spinlock mylock;". The compiler sees a object with a lock() method and calls the right one (might be inlined). No branching at all. If you then want a flat function interface which matches the current one you can make a very simple templates to generate lock() and unlock() functions.
The way Ingo have done it in flat C is by doing making a macro containing "if(TYPE_EQUAL(lock), mutex) lock_mutex((mutex_t*)lock) else if(TYPE_EQUAL(lock, raw_spinlock_t)...." I know, with -O2 this wont actually generate a branching code but it is very, very ugly.
C++ is a huge benifit to people who know C++. It will _not_ make inefficient code unless you use it the wrong way ofcourse (see the above examble). On the contrary you can do more efficient code since you can do
a lot of the stuff compile time. But to avoid complexity stay away trying smart templates combined with operator overloading. THAT is hell figure out when it can't compile. On the other hand when it can compile there are very few errors in the resulting program due to the strong type-checking.
(
Log in to post comments)