|go ahead... be a heretic|
Re: How to use multithreading in perl?by zentara (Archbishop)
|on Apr 12, 2014 at 19:54 UTC||Need Help??|
There are just some very general comments one can make about Perl threads.
The first is not all modules are thread safe, so be cautious when using module code across threads. Many modules are fine though, it depends. Google if in doubt.
Second, since Perl scripts are run by interpreter, memory allocations made by a thread, will be kept by the mother process for later use. So memory gains can be problem. So if you need to reclaim memory during the whole process, it is better to fork.
Third, since Perl threads are made by a copy-on-create method, where the thread is a copy of the mother process at the time of creation, the threads can get alot of useless crud in them, and tend to be slow starting up.
Fourth, it pays to design to reuse your threads. Make the threads once, then just reset them and feed them new data. This is a general way of improving performance and avoiding problems which come from spawning many many threads. But sometimes spawing and detaching works fine. YMMV
Fifth, Perl threads are best suited for situations where you need realtime sharing of data between threads, using shared thread variables. Any other use can usually be done cleaner with a fork.
Signals can be tricky. The mother thread receives all signals, and it is up to you to pass it on to the correct thread.
I'm just an amateur, and I tend to manually control my threads, but are some useful examples of mine and other monks: Using Select and pipes to communicate with threads .... using the thread->kill() feature on linux .... Interrupting a blocking read (Linux::Inotify2) with a signal handler within a thread ... How to wake a thread in Perl .... Simple threaded chat server ... Re: Passing objects between threads...any solutions? (shared objects) .... Reusable threads demo
Those ought to get you started. :-) Good luck.
P.S. As you google for examples, look for the answers from BrowserUk. He has the best understanding.