Multi-threaded Perl
I recently had a chance to work on some multi-threaded perl via forking and child processes. The idea is to spawn multple processes to handle doing multiple tasks simultaneously. This is useful in many cases. In my particular application, I had a script that was checking a list of servers for connectivity (essentially a ‘ping’), and alarm if unreachable.
A few sites that were helpful to me:
perldoc.perl.org/functions/fork.html
www.perlmonks.org/index.pl?node_id=43497
The coding can look a little weird, but when you call “fork”, you end up with a complete duplicate of the process – code, variables, etc. The new process (child) starts executing from the fork call, and usually you immediately test to see whether you are the parent or the child, and go from there. The child should exit after doing it’s job. The parent needs to check periodically (or wait) for its child processes to “die” (yes, that’s the terminology), or you will create zombie processes (yes, that’s what they are called) on the server – not a good idea. For this, you’ll want to implement “waitpid()”, shown in the example site referenced above. Once all the children are spawned, the parent process needs to loop, collecting the dead child processes to clean things up properly.
Forking is a useful technique to learn, and isn’t hard once you understand the concepts involved.
Comments Off on Multi-threaded Perl | Programming