简体   繁体   中英

Multithreading for perl code

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 script call itself after every 3 seconds. But i need to call it every second , can anybody provide me a solution to it or point me to right direction.

#!usr/bin/perl
use warnings;

sub print
{
local $gg = time;
print "$gg\n";
}

$oldtime = (time + 1);
while(1)
{
if(time > $oldtime)
{
    &print();
    sleep 2;
    $oldtime = (time + 1);
            }
        }

Its just an example.

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 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.
  • Avoid giving subroutines the same name as system functions (eg 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM