death114 发表于 2018-8-30 10:52:22

perl使用Mojolicious设置threads查看设置参数

use Mojolicious::Lite;  
use threads;
  
use threads::shared;
  
#请直接使用 ./x.pl daemon 启动
  
#morbo启动,线程不会自动关闭。要手动关闭改代码才行,不然创建的线程仍会执行
  
#当然你的线程不是个死循环,使用morbo也是不错的。线程执行完就会自动退出
  
#当然你可以使用其他方式避免线程句柄被重置。
  

  
#线程共享变量,
  
my $signal:shared=-1;
  
my $i:shared=0;
  
#线程句柄
  
my $thr;
  

  
#接受POST GET都是它。
  
any '/status' => sub {
  
my $c = shift;
  
#只要模块里有要使用的,即使是空值都要传过去,不然在模块里会报错。
  
#Global symbol "$xxx" requires explicit package name
  
$c->stash(status => $signal);
  
$c->stash(i => $i);
  
$c->stash(thr => $thr);
  
#数据限制。状态设置,判断参数使用字符串判断是否为空
  
if ($c->param('signal') ne '' && $c->param('signal') >=-1 && $c->param('signal')param('signal');
  
$c->stash(status => $signal);
  
undef $thr if $signal == -1 ;
  
$c->stash(thr => $thr);
  
}
  
#根据传进来的参数创建线程
  
if ($c->param('action')) {
  
    my $action=$c->param('action');
  
    if ($action eq 'create') {
  
      $thr = threads->new(\&ppp,1) unless $thr ;
  
      $c->stash(thr => $thr);
  
    }
  
}
  
$c->render('status');
  
};
  

  
#线程函数
  
sub ppp {
  
#接受第一个参数
  
    $signal=shift;
  
#0的时候跟false一样
  
    while($signal or $signal==0){
  
#睡一秒钟
  
      sleep 1;
  
      last if $signal == -1;
  
#再睡一秒钟
  
      sleep 1 if $signal == 0;
  
#print要换行符才会有输出,不然要等到mojo结束了才有输出。
  
      print "running.\t.".$i++."\n" if ($signal == 1 )
  

  
    }
  
}
  
app->start;
  

  
__DATA__
  
@@ status.html.ep
  
% unless ($thr) {
  
no threads creat or threads down bbbba
  
%} else {
  

  
%}
  
The status Can be exit=-1stop=0 start=1
  
The status now is   .i= .thr=
  
%= form_for '/status' => (method => 'POST') => begin
  
%= text_field 'signal'
  
%= submit_button '设置状态'
  
% end
  
%= form_for '/status' => (method => 'POST') => begin
  
%= hidden_field action => 'create'
  
%= submit_button '创建线程'
  
% end


页: [1]
查看完整版本: perl使用Mojolicious设置threads查看设置参数