I’m trying to write a server program which can keep a track of the number of instances of some object.
At the moment I’m using a static int which is incremented during the object’s constructor:
class myObj{
public:
static int numOfInstances;
myObj();
};
int myObj::numOfInstances = 0;
myObj::myObj(){
this->numOfInstances = ++myObj::numOfInstaces
}
But I also want to fork for each connection, with a child process handling each one and the parent constantly listening for new connections.
If I use fork(), each child process is unaware of new connections, and new objects created due to them.
I think threading might be a solution, but I’m not sure if threading is cut out for this kind of thing (most of the program would run in the thread). Even if it is, it’s not in the ANSI standard, so I’d rather find a solution which uses fork.
If there’s no sane solution with fork, which threading solution do people recommend? I’m writing for Linux, but I’d much prefer a cross-platform solution.
Multiprocessing is not part of the C++ standard. However, if you are on a POSIX system (where you have
fork()), you can obtain shared memory from the operating system; look at theshmget()familiy of functions. You will need some synchronisation mechanism for access to the shared memory (like a mutex or a semaphore); those are also provided.I suggest
man shm_overviewandman sem_overviewas starting points.