Perl代码的多线程 [英] Multithreading for perl code
问题描述
我需要知道如何为以下代码实现多线程.我需要每秒调用一次此脚本,但是睡眠计时器会在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 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).
这篇关于Perl代码的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!