Perl Thread

perldoc threads  ----  英文的... ...

网上找不到中文全面介绍的,无奈,哥今天就来翻译一下。

<<=========================threads===========================>>

#!/usr/bin/perl
use threads ('yield',
            'stack_size' => 64*4096,
            'exit' => 'threads_only',
            'stringify');

sub start_thread {
   my @args = @_;
   print('Thread started: ', join(' ', @args), "\n");
}

##创建线程的方法
# my $thr = threads->create('func_name', ...);
# my $thr = threads->create(sub { ... }, ...);
# my $thr = threads->create(\&func, ...);
# The "->new()" method is an alias for "->create()".
my $thr = threads->create('start_thread', 'argument1', 'argument2');		#通过create创建线程。返回线程实例
$thr->join();				#等待线程结束
threads->create(sub { print("I am a thread\n"); })->join();					#创建一个线程,没有返回值。那这个线程实例如何访问呢?

my $thr2 = async { foreach (@ARGS) { print"$_\n"; } };								#通过async使用匿名子例程创建线程
$thr2->join();
if (my $err = $thr2->error()) {
   warn("Thread error: $err\n");
}

# 在隐式的列表环境中调用thread
my $thr3 = threads->create(sub { return (qw/a b c/); });
# 在显式的列表环境中调用thread
my $thr4 = threads->create({'context' => 'list'},
                         sub { return (qw/a b c/); });
# 由于创建线程时使用的子例程返回的是列表,所以这里的join函数返回的也是列表
my @results = $thr3->join();
print "@results\n";
# 把线程从主线程中分离出来
# $thr->detach();		##报错:Cannot detach a joined thread,因为$thr已经调用过join()
$thr4->detach();		##
$tid = $thr4->tid();
print "线程4ID:$tid\n";

# Get a thread's object
$thr6 = threads->self();
$thr7 = threads->object($tid);

# Get a thread's ID
$tid = threads->tid();
$tid = "$thr7";		#根据线程实例获得线程ID

# 给其他线程一个运行的机会
threads->yield();
yield();

# 返回未分离的线程列表
my @threads = threads->list();
my $thread_count = threads->list();

my @running = threads->list(threads::running);
my @joinable = threads->list(threads::joinable);

# 判断两个线程是相同
if ($thr4 == $thr2) {
   print "thread4 equals to thread2.\n";
}

# 管理线程栈大小
$stack_size = threads->get_stack_size();
$old_size = threads->set_stack_size(32*4096);

# Create a thread with a specific context and stack size
my $thr5 = threads->create({ 'context'    => 'list',
                           'stack_size' &
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值