用于perl代码的多线程

New*_*Bee 13 perl multithreading

我需要知道如何为以下代码实现多线程.我需要每秒调用一次这个脚本,但睡眠定时器会在2秒后处理它.在每3秒后完成脚本调用.但我需要每隔一段时间调用一次,任何人都可以为我提供解决方案或指向正确的方向.

#!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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

这只是一个例子.

小智 36

这是一个使用线程的简单示例:

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;
}
Run Code Online (Sandbox Code Playgroud)

这将每秒创建一个线程.线程本身持续两秒钟.

要了解有关线程的更多信息,请参阅文档.一个重要的考虑因素是线程之间不共享变量.当您启动新线程时,会创建所有变量的重复副本.

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

但请注意,正确的设计取决于您实际要做的事情.你的问题并不清楚.

对您的代码的其他一些评论:

  • 始终use strict;帮助您在代码中使用最佳实践.
  • 声明词法变量的正确方法my $gg;不是local $gg;.local实际上并没有创建一个词法变量; 它为全局变量提供了本地化值.这不是你需要经常使用的东西.
  • 避免给子程序提供与系统功能相同的名称(例如print).这令人困惑.
  • 不建议&在调用子例程之前使用(在您的情况下,由于与系统函数名称冲突,这是必要的,但正如我所说,应该避免).