Cross-Platform Threading/Forking-with-static-variables in C/C++
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 the shmget()
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_overview
and man sem_overview
as starting points.
I don't really know how resource sharing works on POSIX systems (so I can't tell you whether to simply fork()
or use threads) but there's the portable Boost.Thread library, in addition to pthreads, if you decide to go that way.
Note that there's also a race condition in your code; two threads (whether in the same process or not, so in either case) cannot write to the same location without some kind of synchronization.
精彩评论