Multithreading for perl code
Here is a simple example of using threads:
use strict;use warnings;use threads;sub threaded_task { threads->create(sub { my $thr_id = threads->self->tid; print "Starting thread $thr_id\n"; sleep 2; print "Ending thread $thr_id\n"; threads->detach(); #End thread. });}while (1){ threaded_task(); sleep 1;}
This will create a thread every second. The thread itself lasts two seconds.
To learn more about threads, please see the documentation. An important consideration is that variables are not shared between threads. Duplicate copies of all your variables are made when you start a new thread.
If you need shared variables, look into threads::shared
.
However, please note that the correct design depends on what you are actually trying to do. Which isn't clear from your question.
Some other comments on your code:
- Always
use strict;
to help you use best practices in your code. - The correct way to declare a lexical variable is
my $gg;
rather thanlocal $gg;
.local
doesn't actually create a lexical variable; it gives a localized value to a global variable. It is not something you will need to use very often. - Avoid giving subroutines the same name as system functions (e.g.
print
). This is confusing. - It is not recommended to use
&
before calling subroutines (in your case it was necessary because of conflict with a system function name, but as I said, that should be avoided).