Perl代码的多线程 [英] Multithreading for perl code

查看:92
本文介绍了Perl代码的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何为以下代码实现多线程.我需要每秒调用一次此脚本,但是睡眠计时器会在2秒后对其进行处理.总的来说,脚本每隔3秒就会调用一次.但是我需要每秒调用一次,有人可以为我提供解决方案还是可以为我指明正确的方向.

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);
            }
        }

这只是一个例子.

推荐答案

以下是使用线程的简单示例:

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.

如果需要共享变量,请查看threads::shared .

If you need shared variables, look into threads::shared.

但是,请注意正确的设计取决于您实际尝试做的事情.您的问题不清楚哪一个.

关于您的代码的其他注释:

Some other comments on your code:

  • 始终use strict;可以帮助您在代码中使用最佳做法.
  • 声明词法变量的正确方法是my $gg;而不是local $gg;. local实际上并没有创建词汇变量.它为全局变量提供了局部值.您不需要经常使用它.
  • 避免为子例程提供与系统函数相同的名称(例如print).这很令人困惑.
  • 不建议在调用子例程之前使用&(在您的情况下,由于与系统功能名称冲突,因此有必要,但正如我所说,应避免使用该语言).
  • 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 (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).

这篇关于Perl代码的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆