I need to know how to implement multi threading for the following code . I need to call this script every second but the sleep timer processes it after 2 seconds . In total scri
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:
use strict;
to help you use best practices in your code.my $gg;
rather than local $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.print
). This is confusing.&
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).