Linked by Eugenia Loli on Mon 14th Nov 2005 06:11 UTC
Linux Making effective use of shared memory in high-level languages such as C++ is not straightforward, but it is possible to overcome the inherent difficulties. This article describes, and includes sample code for, two C++ design patterns that use shared memory on Linux in interesting ways and open the door for more efficient interprocess communication.
Permalink for comment 60004
To read all comments associated with this story, please click here.
by japail on Mon 14th Nov 2005 17:03 UTC
Member since:

From a casual perusal of this article:

1. shmat returns -1 on an error, not NULL so the error handling there is broken.

2. strncpy is successfully used in a broken manner.

3. The sharing of the mutex here is completely broken. Every process has its own instance of Initializer and the mutex belongs to this instance. The shared datastructure is thus not synchronized.

4. Virtual functions are pointlessly used in the singleton. For one the base class contains the nonparameterized factory method for constructing instances of the subclass, which actually depends on the existence of an instance of Initialize to do all of the work of ensuring that an instance is available. There is no clear 'interface' and 'concrete' classes, and share a pointless vtable.

5. The allocation strategy is baroque and retarded. If you wish to use the factory pattern for providing concrete instances of abstract base classes, you should probably go ahead and really do that. The sloppiness here with constructors/destructors and the usage of virtual is dangerous. Further the way new is overloaded happens to be particularly bad, and the usage here of a limited resource (shared memory segments) is also in bad style. If you insisted on using this style of constructing instances of classes into shared memory segments, and had need of multiple singletons creating a general shared memory allocator and then using that in parameterized factories is the best approach. Doing this correctly you could actually provide trivial (and inefficient) synchronization with a smart pointer that makes use of a semaphore.

6. This code creates a shared memory segment that's never cleaned up. You'll have to use ipcrm to get rid of that sucker. If you do anything to change the layout of the class without manually removing the segment you'll probably find yourself with a lot of segfaults. Which just exposes the extreme brittleness of this approach as demonstrated, even without leaving a junk segment floating around.

7. This is actually not an especially efficient form of IPC, especially not with this example.

P.S. Please, continue using char* for strings in 2005. It hasn't caused enough harm yet.

Edited 2005-11-14 17:10

Reply Score: 5